<?php
/***************************************************************************
*                            Dolphin Smart Community Builder
*                              -------------------
*     begin                : Mon Mar 23 2006
*     copyright            : (C) 2007 BoonEx Group
*     website              : http://www.boonex.com
* This file is part of Dolphin - Smart Community Builder
*
* Dolphin is free software; you can redistribute it and/or modify it under
* the terms of the GNU General Public License as published by the
* Free Software Foundation; either version 2 of the
* License, or  any later version.
*
* Dolphin is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY;
* without even the implied warranty of  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
* See the GNU General Public License for more details.
* You should have received a copy of the GNU General Public License along with Dolphin,
* see license.txt file; if not, write to marketing@boonex.com
***************************************************************************/

function bx_groups_import ($sClassPostfix, $aModuleOverwright = array()) {
    global $aModule;
    $a = $aModuleOverwright ? $aModuleOverwright : $aModule;
    if (!$a || $a['uri'] != 'groups') {
        $oMain = BxDolModule::getInstance('BxGroupsModule');
        $a = $oMain->_aModule;
    }
    bx_import ($sClassPostfix, $a) ;
}

bx_import('BxDolPaginate');
bx_import('BxDolAlerts');
bx_import('BxDolTwigModule');

define ('BX_GROUPS_PHOTOS_CAT', 'Groups');
define ('BX_GROUPS_PHOTOS_TAG', 'groups');

define ('BX_GROUPS_VIDEOS_CAT', 'Groups');
define ('BX_GROUPS_VIDEOS_TAG', 'groups');

define ('BX_GROUPS_SOUNDS_CAT', 'Groups');
define ('BX_GROUPS_SOUNDS_TAG', 'groups');

define ('BX_GROUPS_FILES_CAT', 'Groups');
define ('BX_GROUPS_FILES_TAG', 'groups');

define ('BX_GROUPS_MAX_FANS', 1000);

/*[begin] map integration*/ 
define ('BX_GROUPS_ZOOM_PROFILES', 10);
define ('BX_GROUPS_ZOOM_CITIES', 5);
define ('BX_GROUPS_ZOOM_COUNTRIES', 1);
define ('BX_GROUPS_DEFAULT_PRIVACY', 3); 
/*[end] map integration*/


/*
 * Groups module
 *
 * This module allow users to create user's groups, 
 * users can rate, comment and discuss group.
 * Group can have photos, videos, sounds and files, uploaded
 * by group's fans and/or admins.
 *
 * 
 *
 * Profile's Wall:
 * 'add group' group is displayed in profile's wall
 *
 *
 *
 * Spy:
 * The following qactivity is displayed for content_activity:
 * add - new group was created
 * change - group was chaned
 * join - somebody joined group
 * rate - somebody rated group
 * commentPost - somebody posted comment in group
 *
 *
 *
 * Memberships/ACL:
 * groups view group - BX_GROUPS_VIEW_GROUP
 * groups browse - BX_GROUPS_BROWSE
 * groups search - BX_GROUPS_SEARCH
 * groups add group - BX_GROUPS_ADD_GROUP
 * groups comments delete and edit - BX_GROUPS_COMMENTS_DELETE_AND_EDIT
 * groups edit any group - BX_GROUPS_EDIT_ANY_GROUP
 * groups delete any group - BX_GROUPS_DELETE_ANY_GROUP
 * groups mark as featured - BX_GROUPS_MARK_AS_FEATURED
 * groups approve groups - BX_GROUPS_APPROVE_GROUPS
 * groups broadcast message - BX_GROUPS_BROADCAST_MESSAGE
 *
 * 
 *
 * Service methods:
 *
 * Homepage block with different groups
 * @see BxGroupsModule::serviceHomepageBlock
 * BxDolService::call('groups', 'homepage_block', array());
 *
 * Profile block with user's groups
 * @see BxGroupsModule::serviceProfileBlock
 * BxDolService::call('groups', 'profile_block', array($iProfileId));
 *
 * Group's forum permissions (for internal usage only)
 * @see BxGroupsModule::serviceGetForumPermission
 * BxDolService::call('groups', 'get_forum_permission', array($iMemberId, $iForumId));
 *
 * Member menu item for groups (for internal usage only)
 * @see BxGroupsModule::serviceGetMemberMenuItem
 * BxDolService::call('groups', 'get_member_menu_item', array());
 *
 *
 *
 * Alerts:
 * Alerts type/unit - 'bx_groups'
 * The following alerts are rised
 *
 *  join - user joined a group
 *      $iObjectId - group id
 *      $iSenderId - joined user
 *
 *  join_request - user want to join a group
 *      $iObjectId - group id
 *      $iSenderId - user id which want to join a group
 *
 *  join_reject - user was rejected to join a group
 *      $iObjectId - group id
 *      $iSenderId - regected user id
 *
 *  fan_remove - fan was removed from a group
 *      $iObjectId - group id
 *      $iSenderId - fan user if which was removed from admins
 *
 *  fan_become_admin - fan become group's admin
 *      $iObjectId - group id
 *      $iSenderId - nerw group's fan user id
 *
 *  admin_become_fan - group's admin become regular fan
 *      $iObjectId - group id
 *      $iSenderId - group's admin user id which become regular fan
 *
 *  join_confirm - group's admin confirmed join request
 *      $iObjectId - group id
 *      $iSenderId - condirmed user id
 *
 *  add - new group was added
 *      $iObjectId - group id
 *      $iSenderId - creator of a group
 *      $aExtras['Status'] - status of added group
 *
 *  change - group's info was changed
 *      $iObjectId - group id
 *      $iSenderId - editor user id
 *      $aExtras['Status'] - status of changed group
 *
 *  delete - group was deleted
 *      $iObjectId - group id
 *      $iSenderId - deleter user id
 *
 *  mark_as_featured - group was marked/unmarked as featured
 *      $iObjectId - group id
 *      $iSenderId - performer id
 *      $aExtras['Featured'] - 1 - if group was marked as featured and 0 - if group was removed from featured 
 *
 */
class BxGroupsModule extends BxDolTwigModule {

    var $_oPrivacy;
    var $_aQuickCache = array ();

    function BxGroupsModule(&$aModule) {

        parent::BxDolTwigModule($aModule);        
        $this->_sFilterName = 'bx_groups_filter';
        $this->_sPrefix = 'bx_groups';

	    $this->_oConfig->init($this->_oDb);

        bx_import ('Privacy', $aModule);
        $this->_oPrivacy = new BxGroupsPrivacy($this);
  
        bx_import ('MapPrivacy', $aModule);
        $this->_oMapPrivacy = new BxGroupsMapPrivacy($this);


		//[begin] - ultimate groups mod from modzzz  
		//reloads states on Add form
		if($_GET['ajax']=='state')
		{
			$sCountryCode = $_GET['country'];
			echo $this->_oDb->getStateOptions($sCountryCode);
			exit;
		}		
		//[end] - ultimate groups mod from modzzz 


        $GLOBALS['oBxGroupsModule'] = &$this;
    }

    function actionHome () {
        parent::_actionHome(_t('_bx_groups_page_title_home'));
    }

    function actionFiles ($sUri) {
        parent::_actionFiles ($sUri, _t('_bx_groups_page_title_files'));
    }

    function actionSounds ($sUri) {
        parent::_actionSounds ($sUri, _t('_bx_groups_page_title_sounds'));
    }

    function actionVideos ($sUri) {
        parent::_actionVideos ($sUri, _t('_bx_groups_page_title_videos'));
    }

    function actionPhotos ($sUri) {
        parent::_actionPhotos ($sUri, _t('_bx_groups_page_title_photos'));
    }

    function actionComments ($sUri) {
        parent::_actionComments ($sUri, _t('_bx_groups_page_title_comments'));
    }

    function actionBrowseFans ($sUri) {
        parent::_actionBrowseFans ($sUri, 'isAllowedViewFans', 'getFansBrowse', $this->_oDb->getParam('bx_groups_perpage_browse_fans'), 'browse_fans/', _t('_bx_groups_page_title_fans'));
    }

    function actionView ($sUri) {
        parent::_actionView ($sUri, _t('_bx_groups_msg_pending_approval'));
    }

    function actionUploadPhotos ($sUri) {        
        parent::_actionUploadMedia ($sUri, 'isAllowedUploadPhotos', 'images', array ('images_choice', 'images_upload'), _t('_bx_groups_page_title_upload_photos'));
    }

    function actionUploadVideos ($sUri) {
        parent::_actionUploadMedia ($sUri, 'isAllowedUploadVideos', 'videos', array ('videos_choice', 'videos_upload'), _t('_bx_groups_page_title_upload_videos'));
    }

    function actionUploadSounds ($sUri) {
        parent::_actionUploadMedia ($sUri, 'isAllowedUploadSounds', 'sounds', array ('sounds_choice', 'sounds_upload'), _t('_bx_groups_page_title_upload_sounds')); 
    }

    function actionUploadFiles ($sUri) {
        parent::_actionUploadMedia ($sUri, 'isAllowedUploadFiles', 'files', array ('files_choice', 'files_upload'), _t('_bx_groups_page_title_upload_files')); 
    }

    function actionBroadcastOLD ($iEntryId) {
        parent::_actionBroadcast ($iEntryId, _t('_bx_groups_page_title_broadcast'), _t('_bx_groups_msg_broadcast_no_recipients'), _t('_bx_groups_msg_broadcast_message_sent'));
    }

    function actionInviteOLD ($iEntryId) {
        parent::_actionInvite ($iEntryId, 'bx_groups_invitation', $this->_oDb->getParam('bx_groups_max_email_invitations'), _t('_bx_groups_msg_invitation_sent'), _t('_bx_groups_msg_no_users_to_invite'), _t('_bx_groups_page_title_invite'));
    }

    function _getInviteParams ($aDataEntry, $aInviter) {
        return array (
                'GroupName' => $aDataEntry['title'],
                'GroupLocation' => _t($GLOBALS['aPreValues']['Country'][$aDataEntry['country']]['LKey']) . (trim($aDataEntry['city']) ? ', '.$aDataEntry['city'] : '') . ', ' . $aDataEntry['zip'],
                'GroupUrl' => BX_DOL_URL_ROOT . $this->_oConfig->getBaseUri() . 'view/' . $aDataEntry['uri'],
                'AcceptUrl' => BX_DOL_URL_ROOT . $this->_oConfig->getBaseUri() . 'accept/' . $aDataEntry['id'], 
				'InviterUrl' => $aInviter ? getProfileLink($aInviter['ID']) : 'javascript:void(0);',
                'InviterNickName' => $aInviter ? $aInviter['NickName'] : _t('_bx_groups_user_unknown'),
                'InvitationText' => stripslashes(strip_tags($_POST['inviter_text'])),
            );        
    }    

    function actionCalendarOLD ($iYear = '', $iMonth = '') {
        parent::_actionCalendar ($iYear, $iMonth, _t('_bx_groups_page_title_calendar'));
    }

    function actionSearchOLD ($sKeyword = '', $sCategory = '') {
        parent::_actionSearch ($sKeyword, $sCategory, _t('_bx_groups_page_title_search'));
    }

    function actionAdd () {
        parent::_actionAdd (_t('_bx_groups_page_title_add'));
    }

    function _addForm ($sRedirectUrl) {

        bx_import ('FormAdd', $this->_aModule);
        $sClass = $this->_aModule['class_prefix'] . 'FormAdd';
        $oForm = new $sClass ($this, $this->_iProfileId);
        $oForm->initChecker();

        if ($oForm->isSubmittedAndValid ()) {

            $sStatus = $this->_oDb->getParam($this->_sPrefix.'_autoapproval') == 'on' || $this->isAdmin() ? 'approved' : 'pending';
            $aValsAdd = array (
                $this->_oDb->_sFieldCreated => time(),
                $this->_oDb->_sFieldUri => $oForm->generateUri(),
                $this->_oDb->_sFieldStatus => $sStatus,
            );                        
            $aValsAdd[$this->_oDb->_sFieldAuthorId] = $this->_iProfileId;

            $iEntryId = $oForm->insert ($aValsAdd);

            if ($iEntryId) {

                $this->isAllowedAdd(true); // perform action                 

				//rss mod
				$this->_oDb->addRss($iEntryId);

                $oForm->processMedia($iEntryId, $this->_iProfileId);

                $aDataEntry = $this->_oDb->getEntryByIdAndOwner($iEntryId, $this->_iProfileId, $this->isAdmin());
                $this->onEventCreate($iEntryId, $sStatus, $aDataEntry);
                if (!$sRedirectUrl)
                    $sRedirectUrl = BX_DOL_URL_ROOT . $this->_oConfig->getBaseUri() . 'view/' . $aDataEntry[$this->_oDb->_sFieldUri];
                header ('Location:' . $sRedirectUrl);
                exit;

            } else {

                MsgBox(_t('_Error Occured'));
            }
                         
        } else {
            
            echo $oForm->getCode ();

        }
    }
 
    function actionEdit ($iEntryId) {
        $this->_actionEdit ($iEntryId, _t('_bx_groups_page_title_edit'));
    }

    function _actionEdit ($iEntryId, $sTitle) { 

        $iEntryId = (int)$iEntryId;
        if (!($aDataEntry = $this->_oDb->getEntryById($iEntryId))) {
            $this->_oTemplate->displayPageNotFound ();
            return;
        }

        $GLOBALS['oTopMenu']->setCustomSubHeader($aDataEntry[$this->_oDb->_sFieldTitle]);
        $GLOBALS['oTopMenu']->setCustomVar($this->_sPrefix.'_view_uri', $aDataEntry[$this->_oDb->_sFieldUri]);
        $GLOBALS['oTopMenu']->setCustomBreadcrumbs(array(
            _t('_'.$this->_sPrefix) => BX_DOL_URL_ROOT . $this->_oConfig->getBaseUri() . 'home/',
            $aDataEntry[$this->_oDb->_sFieldTitle] => BX_DOL_URL_ROOT . $this->_oConfig->getBaseUri() . 'view/' . $aDataEntry[$this->_oDb->_sFieldUri],
            $sTitle => '',
        ));

        if (!$this->isAllowedEdit($aDataEntry)) {
            $this->_oTemplate->displayAccessDenied ();
            return;
        }

        $this->_oTemplate->pageStart();

        bx_import ('FormEdit', $this->_aModule);
        $sClass = $this->_aModule['class_prefix'] . 'FormEdit';
        $oForm = new $sClass ($this, $aDataEntry[$this->_oDb->_sFieldAuthorId], $iEntryId, $aDataEntry);
        if (isset($aDataEntry[$this->_oDb->_sFieldJoinConfirmation]))
            $aDataEntry[$this->_oDb->_sFieldJoinConfirmation] = (int)$aDataEntry[$this->_oDb->_sFieldJoinConfirmation];
        
        $oForm->initChecker($aDataEntry);

        if ($oForm->isSubmittedAndValid ()) {

            $sStatus = $this->_oDb->getParam($this->_sPrefix . '_autoapproval') == 'on' || $this->isAdmin() ? 'approved' : 'pending';
            $aValsAdd = array ($this->_oDb->_sFieldStatus => $sStatus);
            if ($oForm->update ($iEntryId, $aValsAdd)) {
 
				if( is_array($_POST['prev_feed']) &&count($_POST['prev_feed'])){
					$aFeeds2Keep = array();

					foreach ($_POST['prev_feed'] as $iFeedId){
						$aFeeds2Keep[$iFeedId] = $iFeedId;
					}

					$aFeedIds = $this->_oDb->getRssIds($iEntryId);
				
					$aDeletedFeed = array_diff ($aFeedIds, $aFeeds2Keep);

					if ($aDeletedFeed) {
						foreach ($aDeletedFeed as $iFeedId) {
							$this->_oDb->removeRss($iEntryId, $iFeedId);
						}
					}
			  
					$this->_oDb->addRss($iEntryId);
				}

                $oForm->processMedia($iEntryId, $this->_iProfileId);

                $this->isAllowedEdit($aDataEntry, true); // perform action

                $this->onEventChanged ($iEntryId, $sStatus);
                header ('Location:' . BX_DOL_URL_ROOT . $this->_oConfig->getBaseUri() . 'view/' . $aDataEntry[$this->_oDb->_sFieldUri]);
                exit;

            } else {

                echo MsgBox(_t('_Error Occured'));
                
            }            

        } else {

            echo $oForm->getCode ();

        }

        $this->_oTemplate->addJs ('main.js');
        $this->_oTemplate->addCss ('main.css');
        $this->_oTemplate->addCss ('forms_extra.css');
        $this->_oTemplate->pageCode($sTitle);
    }

    function onEventCreate ($iEntryId, $sStatus, $aDataEntry = array()) {

		$this->serviceUpdateProfileLocation ($iEntryId);
 
        if ('approved' == $sStatus) {
            $this->reparseTags ($iEntryId);
            $this->reparseCategories ($iEntryId);
        }
        $this->_oDb->createForum ($aDataEntry, $this->_oDb->getProfileNickNameById($this->_iProfileId));
		$oAlert = new BxDolAlerts($this->_sPrefix, 'add', $iEntryId, $this->_iProfileId, array('Status' => $sStatus));
		$oAlert->alert();
    }

    function onEventChanged ($iEntryId, $sStatus) {

		$this->serviceUpdateProfileLocation ($iEntryId);

        $this->reparseTags ($iEntryId);
        $this->reparseCategories ($iEntryId);

		$oAlert = new BxDolAlerts($this->_sPrefix, 'change', $iEntryId, $this->_iProfileId, array('Status' => $sStatus));
		$oAlert->alert();
    }   


    function actionDelete ($iEntryId) {
        parent::_actionDelete ($iEntryId, _t('_bx_groups_msg_group_was_deleted'));
    }

    function actionMarkFeatured ($iEntryId) {
        parent::_actionMarkFeatured ($iEntryId, _t('_bx_groups_msg_added_to_featured'), _t('_bx_groups_msg_removed_from_featured'));
    }

    function actionJoinOLD ($iEntryId, $iProfileId) {

        parent::_actionJoin ($iEntryId, $iProfileId, _t('_bx_groups_msg_joined_already'), _t('_bx_groups_msg_joined_request_pending'), _t('_bx_groups_msg_join_success'), _t('_bx_groups_msg_join_success_pending'), _t('_bx_groups_msg_leave_success'));
    }    

    function actionSharePopup ($iEntryId) {
        parent::_actionSharePopup ($iEntryId, _t('_bx_groups_caption_share_group'));
    }

    function actionManageFansPopup ($iEntryId) {
        parent::_actionManageFansPopup ($iEntryId, _t('_bx_groups_caption_manage_fans'), 'getFans', 'isAllowedManageFans', 'isAllowedManageAdmins', BX_GROUPS_MAX_FANS);
    }

    function actionTags() {
        parent::_actionTags (_t('_bx_groups_page_title_tags'));
    }    

    function actionCategories() {
        parent::_actionCategories (_t('_bx_groups_page_title_categories'));
    }    

    function actionDownload ($iEntryId, $iMediaId) {

        $aFileInfo = $this->_oDb->getMedia ((int)$iEntryId, (int)$iMediaId, 'files');

        if (!$aFileInfo || !($aDataEntry = $this->_oDb->getEntryByIdAndOwner((int)$iEntryId, 0, true))) {
            $this->_oTemplate->displayPageNotFound ();
            exit;
        }

        if (!$this->isAllowedView ($aDataEntry)) {
            $this->_oTemplate->displayAccessDenied ();
            exit;
        }

        parent::_actionDownload($aFileInfo, 'media_id');
    }

    // ================================== external actions

    /**
     * Homepage block with different groups
     * @return html to display on homepage in a block
     */     
    function serviceHomepageBlock () {

        if (!$this->_oDb->isAnyPublicContent())
            return '';
        
        bx_import ('PageMain', $this->_aModule);
        $o = new BxGroupsPageMain ($this);
        $o->sUrlStart = BX_DOL_URL_ROOT . '?';

        $sDefaultHomepageTab = $this->_oDb->getParam('bx_groups_homepage_default_tab');
        $sBrowseMode = $sDefaultHomepageTab;
        switch ($_GET['bx_groups_filter']) {            
            case 'featured':
            case 'recent':
            case 'top':
            case 'popular':
            case $sDefaultHomepageTab:            
                $sBrowseMode = $_GET['bx_groups_filter'];
                break;
        }

        return $o->ajaxBrowse(
            $sBrowseMode,
            $this->_oDb->getParam('bx_groups_perpage_homepage'), 
            array(
                _t('_bx_groups_tab_featured') => array('href' => BX_DOL_URL_ROOT . '?bx_groups_filter=featured', 'active' => 'featured' == $sBrowseMode, 'dynamic' => true),
                _t('_bx_groups_tab_recent') => array('href' => BX_DOL_URL_ROOT . '?bx_groups_filter=recent', 'active' => 'recent' == $sBrowseMode, 'dynamic' => true),
                _t('_bx_groups_tab_top') => array('href' => BX_DOL_URL_ROOT . '?bx_groups_filter=top', 'active' => 'top' == $sBrowseMode, 'dynamic' => true),
                _t('_bx_groups_tab_popular') => array('href' => BX_DOL_URL_ROOT . '?bx_groups_filter=popular', 'active' => 'popular' == $sBrowseMode, 'dynamic' => true),
            )
        );
    }

    /**
     * Profile block with user's groups
     * @param $iProfileId profile id 
     * @return html to display on homepage in a block
     */     
    function serviceProfileBlock ($iProfileId) {
        $iProfileId = (int)$iProfileId;
        $aProfile = getProfileInfo($iProfileId);
        bx_import ('PageMain', $this->_aModule);
        $o = new BxGroupsPageMain ($this);        
        $o->sUrlStart = getProfileLink($aProfile['ID']) . '?';

        return $o->ajaxBrowse(
            'user', 
            $this->_oDb->getParam('bx_groups_perpage_profile'), 
            array(),
            process_db_input ($aProfile['NickName'], BX_TAGS_NO_ACTION, BX_SLASHES_NO_ACTION),
            true,
            false 
        );
    }

    /**
     * Account page block with groups user joied 
     * @return html to display in a block
     */     
    function serviceAccountJoinedBlock () {
        $iProfileId = (int)$this->_iProfileId;
        $aProfile = getProfileInfo($iProfileId);
        bx_import ('PageMain', $this->_aModule);
        $o = new BxGroupsPageMain ($this);        
        $o->sUrlStart = getProfileLink($aProfile['ID']) . '?';
 
        return $o->ajaxBrowse(
            'joined', 
            $this->_oDb->getParam('bx_groups_perpage_profile'), 
            array(),
            process_db_input ($aProfile['NickName'], BX_TAGS_NO_ACTION, BX_SLASHES_NO_ACTION),
            true,
            false 
        );
    }


    /**
     * Profile block with groups user joied
     * @param $iProfileId profile id 
     * @return html to display on homepage in a block
     */     
    function serviceProfileBlockJoined ($iProfileId) {
        $iProfileId = (int)$iProfileId;
        $aProfile = getProfileInfo($iProfileId);
        bx_import ('PageMain', $this->_aModule);
        $o = new BxGroupsPageMain ($this);        
        $o->sUrlStart = getProfileLink($aProfile['ID']) . '?';

        return $o->ajaxBrowse(
            'joined', 
            $this->_oDb->getParam('bx_groups_perpage_profile'), 
            array(),
            process_db_input ($aProfile['NickName'], BX_TAGS_NO_ACTION, BX_SLASHES_NO_ACTION),
            true,
            false 
        );
    }

    function serviceGetMemberMenuItem () {
        parent::_serviceGetMemberMenuItem (_t('_bx_groups'), _t('_bx_groups'), 'groups.png');
    }

    function serviceGetWallPost ($aEvent) {
        return parent::_serviceGetWallPost ($aEvent, _t('_bx_groups_wall_object'), _t('_bx_groups_wall_added_new'));
    }

    function serviceGetSpyPost($sAction, $iObjectId = 0, $iSenderId = 0, $aExtraParams = array()) {
        return parent::_serviceGetSpyPost($sAction, $iObjectId, $iSenderId, $aExtraParams, array(
            'add' => '_bx_groups_spy_post',
            'change' => '_bx_groups_spy_post_change',
            'join' => '_bx_groups_spy_join',
            'rate' => '_bx_groups_spy_rate',
            'commentPost' => '_bx_groups_spy_comment',
        ));
    }

    function serviceGetSubscriptionParams ($sAction, $iEntryId) {

        $a = array (
            'change' => _t('_bx_groups_sbs_change'),
            'commentPost' => _t('_bx_groups_sbs_comment'),
            'rate' => _t('_bx_groups_sbs_rate'),
            'join' => _t('_bx_groups_sbs_join'),
        );

        return parent::_serviceGetSubscriptionParams ($sAction, $iEntryId, $a);
    }

    // ================================== admin actions

    function actionAdministration ($sUrl = '') {

        if (!$this->isAdmin()) {
            $this->_oTemplate->displayAccessDenied ();
            return;
        }        

        $this->_oTemplate->pageStart();

        $aVars = array (
            'module_url' => BX_DOL_URL_ROOT . $this->_oConfig->getBaseUri(),
        );
        $sContent = $this->_oTemplate->parseHtmlByName ('admin_links', $aVars);
        echo $this->_oTemplate->adminBlock ($sContent, _t('_bx_groups_admin_links'));


        $aMenu = array(
            'pending_approval' => array(
                'title' => _t('_bx_groups_menu_admin_pending_approval'), 
                'href' => BX_DOL_URL_ROOT . $this->_oConfig->getBaseUri() . 'administration/pending_approval', 
                '_func' => array ('name' => 'actionAdministrationManage', 'params' => array(false)),
            ),
            'admin_entries' => array(
                'title' => _t('_bx_groups_menu_admin_entries'), 
                'href' => BX_DOL_URL_ROOT . $this->_oConfig->getBaseUri() . 'administration/admin_entries',
                '_func' => array ('name' => 'actionAdministrationManage', 'params' => array(true)),
            ),            
            'create' => array(
                'title' => _t('_bx_groups_menu_admin_add_entry'), 
                'href' => BX_DOL_URL_ROOT . $this->_oConfig->getBaseUri() . 'administration/create',
                '_func' => array ('name' => 'actionAdministrationCreateEntry', 'params' => array()),
            ),
            'settings' => array(
                'title' => _t('_bx_groups_menu_admin_settings'), 
                'href' => BX_DOL_URL_ROOT . $this->_oConfig->getBaseUri() . 'administration/settings',
                '_func' => array ('name' => 'actionAdministrationSettings', 'params' => array()),
            ),
        );

        if (empty($aMenu[$sUrl]))
            $sUrl = 'pending_approval';

        $aMenu[$sUrl]['active'] = 1;
        $sContent = call_user_func_array (array($this, $aMenu[$sUrl]['_func']['name']), $aMenu[$sUrl]['_func']['params']);

        echo $this->_oTemplate->adminBlock ($sContent, _t('_bx_groups_page_title_administration'), $aMenu);
        $this->_oTemplate->addCssAdmin ('admin.css');
        $this->_oTemplate->addCssAdmin ('unit.css');
        $this->_oTemplate->addCssAdmin ('main.css');
        $this->_oTemplate->addCssAdmin ('forms_extra.css'); 
        $this->_oTemplate->addCssAdmin ('forms_adv.css');        
        $this->_oTemplate->pageCodeAdmin (_t('_bx_groups_page_title_administration'));
    }

    function actionAdministrationSettings () {
        return parent::_actionAdministrationSettings ('Groups');
    }

    function actionAdministrationManage ($isAdminEntries = false) {
        return parent::_actionAdministrationManage ($isAdminEntries, '_bx_groups_admin_delete', '_bx_groups_admin_activate');
    }

    // ================================== events


    function onEventJoinRequest ($iEntryId, $iProfileId, $aDataEntry) {
        parent::_onEventJoinRequest ($iEntryId, $iProfileId, $aDataEntry, 'bx_groups_join_request', BX_GROUPS_MAX_FANS);
    }

    function onEventJoinReject ($iEntryId, $iProfileId, $aDataEntry) {
        parent::_onEventJoinReject ($iEntryId, $iProfileId, $aDataEntry, 'bx_groups_join_reject');
    }

    function onEventFanRemove ($iEntryId, $iProfileId, $aDataEntry) {        
        parent::_onEventFanRemove ($iEntryId, $iProfileId, $aDataEntry, 'bx_groups_fan_remove');
    }

    function onEventFanBecomeAdmin ($iEntryId, $iProfileId, $aDataEntry) {        
        parent::_onEventFanBecomeAdmin ($iEntryId, $iProfileId, $aDataEntry, 'bx_groups_fan_become_admin');
    }

    function onEventAdminBecomeFan ($iEntryId, $iProfileId, $aDataEntry) {        
        parent::_onEventAdminBecomeFan ($iEntryId, $iProfileId, $aDataEntry, 'bx_groups_admin_become_fan');
    }

    function onEventJoinConfirm ($iEntryId, $iProfileId, $aDataEntry) {
        parent::_onEventJoinConfirm ($iEntryId, $iProfileId, $aDataEntry, 'bx_groups_join_confirm');
    }

    // ================================== permissions
    
    function isAllowedViewOLD ($aDataEntry, $isPerformAction = false) {

        // admin and owner always have access
        if ($this->isAdmin() || $aDataEntry['author_id'] == $this->_iProfileId) 
            return true;

        // check admin acl
        $this->_defineActions();
		$aCheck = checkAction($this->_iProfileId, BX_GROUPS_VIEW_GROUP, $isPerformAction);
        if ($aCheck[CHECK_ACTION_RESULT] != CHECK_ACTION_RESULT_ALLOWED)
            return false;

        // check user group 
	    return $this->_oPrivacy->check('view_group', $aDataEntry['id'], $this->_iProfileId); 
    }

    function isAllowedBrowse ($isPerformAction = false) {
        if ($this->isAdmin()) 
            return true;
        $this->_defineActions();
		$aCheck = checkAction($this->_iProfileId, BX_GROUPS_BROWSE, $isPerformAction);
        return $aCheck[CHECK_ACTION_RESULT] == CHECK_ACTION_RESULT_ALLOWED;
    }

    function isAllowedSearch ($isPerformAction = false) {
        if ($this->isAdmin()) 
            return true;
        $this->_defineActions();
		$aCheck = checkAction($this->_iProfileId, BX_GROUPS_SEARCH, $isPerformAction);
        return $aCheck[CHECK_ACTION_RESULT] == CHECK_ACTION_RESULT_ALLOWED;
    }

    function isAllowedAdd ($isPerformAction = false) {
        if ($this->isAdmin()) 
            return true;
        if (!$GLOBALS['logged']['member']) 
            return false;
        $this->_defineActions();
		$aCheck = checkAction($this->_iProfileId, BX_GROUPS_ADD_GROUP, $isPerformAction);
        return $aCheck[CHECK_ACTION_RESULT] == CHECK_ACTION_RESULT_ALLOWED;
    } 

    function isAllowedEdit ($aDataEntry, $isPerformAction = false) {

        if ($this->isAdmin() || ($GLOBALS['logged']['member'] && $aDataEntry['author_id'] == $this->_iProfileId && isProfileActive($this->_iProfileId))) 
            return true;

        // check acl
        $this->_defineActions();
		$aCheck = checkAction($this->_iProfileId, BX_GROUPS_EDIT_ANY_GROUP, $isPerformAction);
        return $aCheck[CHECK_ACTION_RESULT] == CHECK_ACTION_RESULT_ALLOWED;
    } 

    function isAllowedMarkAsFeatured ($aDataEntry, $isPerformAction = false) {
        if ($this->isAdmin()) 
            return true;
        $this->_defineActions();
        $aCheck = checkAction($this->_iProfileId, BX_GROUPS_MARK_AS_FEATURED, $isPerformAction);
        return $aCheck[CHECK_ACTION_RESULT] == CHECK_ACTION_RESULT_ALLOWED;        
    }

    function isAllowedBroadcast ($aDataEntry, $isPerformAction = false) {
        if ($this->isAdmin() || $this->isEntryAdmin($aDataEntry)) 
            return true;
        $this->_defineActions();
        $aCheck = checkAction($this->_iProfileId, BX_GROUPS_BROADCAST_MESSAGE, $isPerformAction);
        return $aCheck[CHECK_ACTION_RESULT] == CHECK_ACTION_RESULT_ALLOWED;        
    }

    function isAllowedDelete (&$aDataEntry, $isPerformAction = false) {
        if ($this->isAdmin() || ($GLOBALS['logged']['member'] && $aDataEntry['author_id'] == $this->_iProfileId && isProfileActive($this->_iProfileId))) 
            return true;
        $this->_defineActions();
		$aCheck = checkAction($this->_iProfileId, BX_GROUPS_DELETE_ANY_GROUP, $isPerformAction);
        return $aCheck[CHECK_ACTION_RESULT] == CHECK_ACTION_RESULT_ALLOWED;
    }     

    function isAllowedJoinOLD (&$aDataEntry) {
        if (!$this->_iProfileId) 
            return false;
        return $this->_oPrivacy->check('join', $aDataEntry['id'], $this->_iProfileId);
    }

    function isAllowedSendInvitation (&$aDataEntry) {
        return $this->isAdmin() || $this->isEntryAdmin($aDataEntry) ? true : false;
    }

    function isAllowedShare (&$aDataEntry) {
        return true;
    }

    function isAllowedPostInForum(&$aDataEntry, $iProfileId = -1) {
        if (-1 == $iProfileId)
            $iProfileId = $this->_iProfileId;
        return $this->isAdmin() || $this->isEntryAdmin($aDataEntry) || $this->_oPrivacy->check('post_in_forum', $aDataEntry['id'], $iProfileId);
    }

    function isAllowedRate(&$aDataEntry) {        
        if ($this->isAdmin())
            return true;
        return $this->_oPrivacy->check('rate', $aDataEntry['id'], $this->_iProfileId);        
    }

    function isAllowedComments(&$aDataEntry) {
        if (!$this->_iProfileId) 
            return false;        
        if ($this->isAdmin())
            return true;
        return $this->_oPrivacy->check('comment', $aDataEntry['id'], $this->_iProfileId);
    }

    function isAllowedViewFans(&$aDataEntry) {
        if ($this->isAdmin())
            return true;
        return $this->_oPrivacy->check('view_fans', $aDataEntry['id'], $this->_iProfileId);
    }

    function isAllowedUploadPhotos(&$aDataEntry) {
        if (!$this->_iProfileId) 
            return false;        
        if ($this->isAdmin())
            return true;
        if (!$this->isMembershipEnabledForImages())
            return false;
        return $this->_oPrivacy->check('upload_photos', $aDataEntry['id'], $this->_iProfileId);
    }

    function isAllowedUploadVideos(&$aDataEntry) {
        if (!$this->_iProfileId) 
            return false;        
        if ($this->isAdmin())
            return true;
        if (!$this->isMembershipEnabledForVideos())
            return false;        
        return $this->_oPrivacy->check('upload_videos', $aDataEntry['id'], $this->_iProfileId);
    }

    function isAllowedUploadSounds(&$aDataEntry) {
        if (!$this->_iProfileId) 
            return false;        
        if ($this->isAdmin())
            return true;
        if (!$this->isMembershipEnabledForSounds())
            return false;                
        return $this->_oPrivacy->check('upload_sounds', $aDataEntry['id'], $this->_iProfileId);
    }

    function isAllowedUploadFiles(&$aDataEntry) {
        if (!$this->_iProfileId) 
            return false;        
        if ($this->isAdmin())
            return true;
        if (!$this->isMembershipEnabledForFiles())
            return false;                        
        return $this->_oPrivacy->check('upload_files', $aDataEntry['id'], $this->_iProfileId);
    }

    function isAllowedCreatorCommentsDeleteAndEdit (&$aDataEntry, $isPerformAction = false) {
        if ($this->isAdmin()) 
            return true;
        if (getParam('bx_groups_author_comments_admin') && $this->isEntryAdmin($aDataEntry))
            return true;
        $this->_defineActions();
		$aCheck = checkAction($this->_iProfileId, BX_GROUPS_COMMENTS_DELETE_AND_EDIT, $isPerformAction);
        return $aCheck[CHECK_ACTION_RESULT] == CHECK_ACTION_RESULT_ALLOWED;
    }

    function isAllowedManageAdmins($aDataEntry) {
        if (($GLOBALS['logged']['member'] || $GLOBALS['logged']['admin']) && $aDataEntry['author_id'] == $this->_iProfileId && isProfileActive($this->_iProfileId))
            return true;
        return false;
    }

    function isAllowedManageFans($aDataEntry) {
        return $this->isEntryAdmin($aDataEntry);
    }

    function isFan($aDataEntry, $iProfileId = 0, $isConfirmed = true) {
        if (!$iProfileId)
            $iProfileId = $this->_iProfileId;
        return $this->_oDb->isFan ($aDataEntry['id'], $iProfileId, $isConfirmed) ? true : false;
    }

    function isEntryAdmin($aDataEntry, $iProfileId = 0) {
        if (!$iProfileId)
            $iProfileId = $this->_iProfileId;
        if (($GLOBALS['logged']['member'] || $GLOBALS['logged']['admin']) && $aDataEntry['author_id'] == $iProfileId && isProfileActive($iProfileId))
            return true;
        return $this->_oDb->isGroupAdmin ($aDataEntry['id'], $iProfileId) && isProfileActive($iProfileId);
    }

    function _defineActions () {
        defineMembershipActions(array('groups purchase featured','groups view group', 'groups rss add', 'groups browse', 'groups search', 'groups add group', 'groups comments delete and edit', 'groups edit any group', 'groups delete any group', 'groups mark as featured', 'groups approve groups', 'groups broadcast message','groups sounds add', 'groups photos add', 'groups videos add', 'groups files add'));
    }

    function _browseMy (&$aProfile) {        
        parent::_browseMy ($aProfile, _t('_bx_groups_page_title_my_groups'));
    }    


   //[start] - ultimate groups mod from modzzz    
    function isAllowedView ($aDataEntry, $isPerformAction = false) {

        // admin and owner always have access
        if ($this->isAdmin() || $aDataEntry['author_id'] == $this->_iProfileId) 
            return true;

        // check admin acl
        $this->_defineActions();
		$aCheck = checkAction($this->_iProfileId, BX_GROUPS_VIEW_GROUP, $isPerformAction);
        if ($aCheck[CHECK_ACTION_RESULT] != CHECK_ACTION_RESULT_ALLOWED)
            return false;

        // check user group  
        $isAllowed =  $this->_oPrivacy->check('view_group', $aDataEntry['id'], $this->_iProfileId);  
        
	return $isAllowed && $this->_isAllowedViewByMembership ($aDataEntry); 

    }

    function _isAllowedViewByMembership (&$aDataEntry) { 
        if (!$aDataEntry['group_membership_view_filter']) return true;
        require_once(BX_DIRECTORY_PATH_INC . 'membership_levels.inc.php');
        $aMembershipInfo = getMemberMembershipInfo($this->_iProfileId);
 
		if($aMembershipInfo['DateExpires']) 
			return $aDataEntry['group_membership_view_filter'] == $aMembershipInfo['ID'] && $aMembershipInfo['DateStarts'] < time() && $aMembershipInfo['DateExpires'] > time() ? true : false;
		else
			return $aDataEntry['group_membership_view_filter'] == $aMembershipInfo['ID'] && $aMembershipInfo['DateStarts'] < time() ? true : false; 
    }
  

    function isAllowedJoin (&$aDataEntry) {        
        if (!$this->_iProfileId) 
            return false;
 
        $isAllowed = $this->_oPrivacy->check('join', $aDataEntry['id'], $this->_iProfileId);     
        return $isAllowed && $this->_isAllowedJoinByMembership ($aDataEntry);
    }

    function _isAllowedJoinByMembership (&$aEvent) {        
        if (!$aEvent['group_membership_filter']) return true;
        require_once(BX_DIRECTORY_PATH_INC . 'membership_levels.inc.php');
        $aMembershipInfo = getMemberMembershipInfo($this->_iProfileId);
        return $aEvent['group_membership_filter'] == $aMembershipInfo['ID'] && $aMembershipInfo['DateStarts'] < time() && $aMembershipInfo['DateExpires'] > time() ? true : false;
    }
 
    function actionBroadcast ($iEntryId) {
        $this->_actionBroadcast ($iEntryId, _t('_bx_groups_page_title_broadcast'), _t('_bx_groups_msg_broadcast_no_recipients'), _t('_bx_groups_msg_broadcast_message_sent'));
    }

    function actionInvite ($iEntryId) {
        $this->_actionInvite ($iEntryId, 'bx_groups_invitation', $this->_oDb->getParam('bx_groups_max_email_invitations'), _t('_bx_groups_msg_invitation_sent'), _t('_bx_groups_msg_no_users_to_invite'), _t('_bx_groups_page_title_invite'));
    }
    function actionCalendar ($iYear = '', $iMonth = '') {

 		if($_GET['ajax']=='cal'){ 
			
			$this->_oTemplate->addCss ('main.css');
			echo $this->displayMainCalendar($iYear, $iMonth, _t('_bx_groups_calendar')); 
  			exit;
		} 
        parent::_actionCalendar ($iYear, $iMonth, _t('_bx_groups_calendar'));
    }

    function actionSearch ($sKeyword = '', $sCategory = '', $sCountry = '', $sState = '', $sCity = '', $sGroupStart = '', $sGroupEnd = '') {

        if (!$this->isAllowedSearch()) {
            $this->_oTemplate->displayAccessDenied ();
            return;
        }

        $this->_oTemplate->pageStart();

        if ($sKeyword) 
            $_GET['keyword'] = $sKeyword;
        if ($sCategory)
            $_GET['categories'] = explode(',', $sCategory);
        if ($sCountry)
            $_GET['country'] = explode(',', $sCountry);
		if ($sState) 
            $_GET['state'] = $sState;
		if ($sCity) 
            $_GET['city'] = $sCity;
 


        if (is_array($_GET['country']) && 1 == count($_GET['country']) && !$_GET['country'][0]) {
            unset($_GET['country']);
            unset($sCountry);
        }

        if (is_array($_GET['categories']) && 1 == count($_GET['categories']) && !$_GET['categories'][0]) {
            unset($_GET['categories']);
            unset($sCategory);
        }
 
        if ($sCountry || $sCategory || $sKeyword || $sState || $sCity ) {
            $_GET['submit_form'] = 1;  
        }
        
        bx_groups_import ('FormSearch');
        $oForm = new BxGroupsFormSearch ();
        $oForm->initChecker();

        if ($oForm->isSubmittedAndValid ()) {
 
            bx_groups_import ('SearchResult');
            $o = new BxGroupsSearchResult('search', $oForm->getCleanValue('Keyword'), $oForm->getCleanValue('Category'), $oForm->getCleanValue('Country'), $oForm->getCleanValue('State'), $oForm->getCleanValue('City'));

            if ($o->isError) {
                $this->_oTemplate->displayPageNotFound ();
                return;
            }

            if ($s = $o->processing()) {
                echo $s;
            } else {
                $this->_oTemplate->displayNoData ();
                return;
            }

            $this->isAllowedSearch(true); // perform search action 

            $this->_oTemplate->addCss ('unit.css');
            $this->_oTemplate->addCss ('main.css');
            $this->_oTemplate->pageCode($o->aCurrent['title'], false, false);
            return;

        } 

        echo $oForm->getCode ();
        $this->_oTemplate->addCss ('main.css');
        $this->_oTemplate->pageCode(_t('_bx_groups_page_title_search'));
    } 
    
    /**
     * Account block with different groups
     * @return html to display on homepage in a block
     */ 
    function serviceAccountPageBlock () {
 
        if (!$this->_oDb->isAnyPublicContent())
            return '';

		$aProfileInfo = getProfileInfo($this->_iProfileId);
		$sCity = $aProfileInfo['City'];

		if(!$sCity)
			return;

        bx_import ('PageMain', $this->_aModule);
        $o = new BxGroupsPageMain ($this);        
        $o->sUrlStart = BX_DOL_URL_ROOT . '?';
 
        return $o->ajaxBrowse(
            'local',
            $this->_oDb->getParam('bx_groups_perpage_accountpage'),
			array(),
			$sCity
        );
    }

    function onGroupCreate ($iEntryId, $sStatus, $aDataEntry = array()) {
        if ('approved' == $sStatus) {
            $this->reparseTags ($iEntryId);
            $this->reparseCategories ($iEntryId);
        }
        $this->_oDb->createForum ($aDataEntry, $this->_oDb->getProfileNickNameById($this->_iProfileId));
		
		$this->_oDb->flagActivity('add', $iEntryId, $this->_iProfileId, array('Status' => $sStatus));
		  
		$oAlert = new BxDolAlerts($this->_sPrefix, 'add', $iEntryId, $this->_iProfileId, array('Status' => $sStatus));
		$oAlert->alert();
    }

    function onGroupChanged ($iEntryId, $sStatus) {
        $this->reparseTags ($iEntryId);
        $this->reparseCategories ($iEntryId);

		$this->_oDb->flagActivity('change', $iEntryId, $this->_iProfileId, array('Status' => $sStatus));

		$oAlert = new BxDolAlerts($this->_sPrefix, 'change', $iEntryId, $this->_iProfileId, array('Status' => $sStatus));
		$oAlert->alert();
    }    

    function onGroupDeleted ($iEntryId, $aDataEntry = array()) {

        // delete associated tags and categories 
        $this->reparseTags ($iEntryId);
        $this->reparseCategories ($iEntryId);

        // delete votings
        bx_import('Voting', $this->_aModule);
        $sClass = $this->_aModule['class_prefix'] . 'Voting';
        $oVoting = new $sClass ($this->_sPrefix, 0, 0);
        $oVoting->deleteVotings ($iEntryId);

        // delete comments 
        bx_import('Cmts', $this->_aModule);
        $sClass = $this->_aModule['class_prefix'] . 'Cmts';
        $oCmts = new $sClass ($this->_sPrefix, $iEntryId);
        $oCmts->onObjectDelete ();

        // delete views
        bx_import ('BxDolViews');
        $oViews = new BxDolViews($this->_sPrefix, $iEntryId, false);
        $oViews->onObjectDelete();

        // delete forum
        $this->_oDb->deleteForum ($iEntryId);

		$this->_oDb->flagActivity('delete', $iEntryId, $this->_iProfileId);

        // arise alert
		$oAlert = new BxDolAlerts($this->_sPrefix, 'delete', $iEntryId, $this->_iProfileId);
		$oAlert->alert();
    }        

    function onEventMarkAsFeatured ($iEntryId, $aDataEntry) {
		
	$this->_oDb->flagActivity('mark_as_featured', $iEntryId, $this->_iProfileId, array('Featured' => $aDataEntry[$this->_oDb->_sFieldFeatured]));

        // arise alert
	$oAlert = new BxDolAlerts($this->_sPrefix, 'mark_as_featured', $iEntryId, $this->_iProfileId, array('Featured' => $aDataEntry[$this->_oDb->_sFieldFeatured]));
	$oAlert->alert();
    }        
 
     function actionJoin ($iEntryId, $iProfileId) {

        $this->_actionJoin ($iEntryId, $iProfileId, _t('_bx_groups_msg_joined_already'), _t('_bx_groups_msg_joined_request_pending'), _t('_bx_groups_msg_join_success'), _t('_bx_groups_msg_join_success_pending'), _t('_bx_groups_msg_leave_success'));
    }   
 
    function _actionJoin ($iEntryId, $iProfileId, $sMsgAlreadyJoined, $sMsgAlreadyJoinedPending, $sMsgJoinSuccess, $sMsgJoinSuccessPending, $sMsgLeaveSuccess) {

        $iEntryId = (int)$iEntryId;
        if (!($aDataEntry = $this->_oDb->getEntryByIdAndOwner($iEntryId, 0, true))) {
            echo MsgBox(_t('_sys_request_page_not_found_cpt')) . genAjaxyPopupJS($iEntryId, 'ajaxy_popup_result_div');
            exit;
        }

        if (!$this->isAllowedJoin($aDataEntry)) { 
            echo MsgBox(_t('_Access denied')) . genAjaxyPopupJS($iEntryId, 'ajaxy_popup_result_div');
            exit;
        }

		$isFan = $this->_oDb->isFan ($iEntryId, $this->_iProfileId, true) || $this->_oDb->isFan ($iEntryId, $this->_iProfileId, false);

		if ($isFan) {

			if ($this->_oDb->leaveEntry($iEntryId, $this->_iProfileId)) {
				
				$this->_oDb->flagActivity('unjoin', $iEntryId, $this->_iProfileId);
		  
				$sRedirect = BX_DOL_URL_ROOT . $this->_oConfig->getBaseUri() . 'view/' . $aDataEntry[$this->_oDb->_sFieldUri];
				echo MsgBox($sMsgLeaveSuccess) . genAjaxyPopupJS($iEntryId, 'ajaxy_popup_result_div', $sRedirect);
				exit;
			}

		} else {
		
			$isConfirmed = ($this->isEntryAdmin($aDataEntry) || !$aDataEntry[$this->_oDb->_sFieldJoinConfirmation] ? true : false);

			if ($this->_oDb->joinEntry($iEntryId, $this->_iProfileId, $isConfirmed)) {
				if ($isConfirmed) {
					
					$this->_oDb->flagActivity('join', $iEntryId, $this->_iProfileId);
		 
					$this->onEventJoin ($iEntryId, $this->_iProfileId, $aDataEntry);
					$sRedirect = BX_DOL_URL_ROOT . $this->_oConfig->getBaseUri() . 'view/' . $aDataEntry[$this->_oDb->_sFieldUri];
				} else {
					$this->onEventJoinRequest ($iEntryId, $this->_iProfileId, $aDataEntry);
					$sRedirect = '';
				}            
				echo MsgBox($isConfirmed ? $sMsgJoinSuccess : $sMsgJoinSuccessPending) . genAjaxyPopupJS($iEntryId, 'ajaxy_popup_result_div', $sRedirect);
				exit;
			}
		}

        echo MsgBox(_t('_Error Occured')) . genAjaxyPopupJS($iEntryId, 'ajaxy_popup_result_div');
        exit;
    }  
	
    function actionAccept ($iEntryId, $iProfileId=0, $sCode='') {
 
		$sMsgJoinSuccess = _t('_bx_groups_msg_join_success');
		$sMsgJoinSuccessPending = _t('_bx_groups_msg_join_success_pending');
		$sMsgJoinRequestPending = _t('_bx_groups_msg_joined_request_pending');

        $this->_oTemplate->pageStart();

        $iEntryId = (int)$iEntryId;
        $iProfileId = (int)$iProfileId;

        if (!$this->_iProfileId) {  
		
			global $_page;
			global $_page_cont;
  
  			$sRedirect = BX_DOL_URL_ROOT . 'member.php';  
			$sRelocate = BX_DOL_URL_ROOT . $this->_oConfig->getBaseUri() . 'accept/' . $iEntryId .'/'. $iProfileId .'/'. $sCode;  

			$_page['name_index'] = 150;
			$_page['css_name'] = '';

			$_ni = $_page['name_index'];
			$_page_cont[$_ni]['page_main_code'] = MsgBox( _t( '_Please Wait' ) );
			$_page_cont[$_ni]['url_relocate'] = htmlspecialchars( $sUrlRelocate );
  
		    Redirect($sRedirect, array('ID' =>'', 'Password' => '', 'relocate' => $sRelocate));   
			PageCode();
			
			return;
        }
 
        if ($iProfileId && ($iProfileId != $this->_iProfileId)) {
            echo MsgBox(_t('_Access denied')); 
			$this->_oTemplate->addCss ('main.css');
			$this->_oTemplate->pageCode(_t('_bx_groups_accept_invitation') . $aDataEntry[$this->_oDb->_sFieldTitle]);
			return; 
        }
 
        if (!($aDataEntry = $this->_oDb->getEntryById($iEntryId))) {
            $this->_oTemplate->displayPageNotFound ();
            return;
        }

		$isFan = $this->_oDb->isFan ($iEntryId, $this->_iProfileId, true); 
		if ($isFan) { 
			//fan already 
			$sRedirect = BX_DOL_URL_ROOT . $this->_oConfig->getBaseUri() . 'view/' . $aDataEntry[$this->_oDb->_sFieldUri];  
			header('Location: ' . $sRedirect); 
			return;
		} 

		$isFan = $this->_oDb->isFan ($iEntryId, $this->_iProfileId, false); 
		if ($isFan) { 
			//fan pending 
			echo MsgBox($sMsgJoinRequestPending); 
			$this->_oTemplate->addCss ('main.css');
			$this->_oTemplate->pageCode(_t('_bx_groups_accept_invitation') . $aDataEntry[$this->_oDb->_sFieldTitle]);
			return;
		} 

        if (!$this->_oDb->isValidInvite($iEntryId, $sCode)) { 
            echo MsgBox(_t('_Access denied')); 
			$this->_oTemplate->addCss ('main.css');
			$this->_oTemplate->pageCode(_t('_bx_groups_accept_invitation') . $aDataEntry[$this->_oDb->_sFieldTitle]);
			return; 
        }
  
		$isConfirmed = ($this->isEntryAdmin($aDataEntry) || !$aDataEntry[$this->_oDb->_sFieldJoinConfirmation] ? true : false);

		if ($this->_oDb->joinEntry($iEntryId, $this->_iProfileId, $isConfirmed)) {
			if ($isConfirmed) {
				
				$this->_oDb->flagActivity('join', $iEntryId, $this->_iProfileId);
	 
				$this->_oDb->removeInvite($iEntryId, $iProfileId);

				$this->onEventJoin ($iEntryId, $this->_iProfileId, $aDataEntry);
				$sRedirect = BX_DOL_URL_ROOT . $this->_oConfig->getBaseUri() . 'view/' . $aDataEntry[$this->_oDb->_sFieldUri];

				header('Location: ' . $sRedirect);
			} else {
				$this->onEventJoinRequest ($iEntryId, $this->_iProfileId, $aDataEntry);
		 
				$this->_oDb->removeInvite($iEntryId, $iProfileId);

				echo MsgBox($sMsgJoinSuccessPending); 
				$this->_oTemplate->addCss ('main.css');
				$this->_oTemplate->pageCode(_t('_bx_groups_accept_invitation') . $aDataEntry[$this->_oDb->_sFieldTitle]);
				return;
			}
		}
	 
        echo MsgBox(_t('_Error Occured'));
 
        $this->_oTemplate->addCss ('main.css');
        $this->_oTemplate->pageCode(_t('_bx_groups_accept_invitation') . $aDataEntry[$this->_oDb->_sFieldTitle]); 
    }    
   
 
    function _onGroupFanRemove ($iEntryId, $iProfileId, $aDataEntry, $sEmailTemplate) {
        
		$this->_oDb->flagActivity('unjoin', $iEntryId, $iProfileId);
		
		$this->_notifyEmail ($sEmailTemplate, $iProfileId, $aDataEntry);
		$oAlert = new BxDolAlerts($this->_sPrefix, 'fan_remove', $iEntryId, $iProfileId);
		$oAlert->alert();        
    }

    function _onGroupFanBecomeAdmin ($iEntryId, $iProfileId, $aDataEntry, $sEmailTemplate) {
        
		$this->_oDb->flagActivity('makeAdmin', $iEntryId, $iProfileId);
	
		$this->_notifyEmail ($sEmailTemplate, $iProfileId, $aDataEntry);
		$oAlert = new BxDolAlerts($this->_sPrefix, 'fan_become_admin', $iEntryId, $iProfileId);
		$oAlert->alert();        
    }

    function _onGroupAdminBecomeFan ($iEntryId, $iProfileId, $aDataEntry, $sEmailTemplate) {
        
		$this->_oDb->flagActivity('removeAdmin', $iEntryId, $iProfileId);
		 
		$this->_notifyEmail ($sEmailTemplate, $iProfileId, $aDataEntry);
		$oAlert = new BxDolAlerts($this->_sPrefix, 'admin_become_fan', $iEntryId, $iProfileId);
		$oAlert->alert();        
    }

    function _onGroupJoinConfirm ($iEntryId, $iProfileId, $aDataEntry, $sEmailTemplate) {
        
		$this->_oDb->flagActivity('join', $iEntryId, $this->_iProfileId);
		
		$this->_notifyEmail ($sEmailTemplate, $iProfileId, $aDataEntry);
		$oAlert = new BxDolAlerts($this->_sPrefix, 'join_confirm', $iEntryId, $iProfileId);
		$oAlert->alert();        
    }


    function actionLocal ($sCountry='', $sState='') { 
        $this->_oTemplate->pageStart();
        bx_import ('PageLocal', $this->_aModule);
        $sClass = $this->_aModule['class_prefix'] . 'PageLocal';
        $oPage = new $sClass ($this, $sCountry, $sState);
        echo $oPage->getCode();
        $this->_oTemplate->addCss ('main.css');
        $this->_oTemplate->addCss ('unit.css');
         $this->_oTemplate->pageCode(_t('_bx_groups_page_title_local'), false, false);
    } 
 
   function _actionBroadcast ($iEntryId, $sTitle, $sMsgNoRecipients, $sMsgSent) {

		global $tmpl;
		require_once( BX_DIRECTORY_PATH_ROOT . 'templates/tmpl_' . $tmpl . '/scripts/BxTemplMailBox.php');
 
        $iEntryId = (int)$iEntryId;
        if (!($aDataEntry = $this->_oDb->getEntryById($iEntryId))) {
            $this->_oTemplate->displayPageNotFound ();
            return;
        }

        if (!$this->isAllowedBroadcast($aDataEntry)) {
            $this->_oTemplate->displayAccessDenied ();
            return;
        }

        $this->_oTemplate->pageStart();

        $GLOBALS['oTopMenu']->setCustomSubHeader($aDataEntry[$this->_oDb->_sFieldTitle]);
        $GLOBALS['oTopMenu']->setCustomVar($this->_sPrefix.'_view_uri', $aDataEntry[$this->_oDb->_sFieldUri]);
        
		if(!(($GLOBALS['site']['ver']=='7.0') && ($GLOBALS['site']['build']=='0'))) {  		
			$GLOBALS['oTopMenu']->setCustomBreadcrumbs(array(
				_t('_'.$this->_sPrefix) => BX_DOL_URL_ROOT . $this->_oConfig->getBaseUri() . 'home/',
				$aDataEntry[$this->_oDb->_sFieldTitle] => BX_DOL_URL_ROOT . $this->_oConfig->getBaseUri() . 'view/' . $aDataEntry[$this->_oDb->_sFieldUri],
				$sTitle => '',
			));
		}

        $aRecipients = $this->_oDb->getBroadcastRecipients ($iEntryId);
        if (!$aRecipients) {
            echo MsgBox ($sMsgNoRecipients);
            $this->_oTemplate->pageCode($sMsgNoRecipients, true, true);
            return;
        }

        bx_import ('FormBroadcast', $this->_aModule);
        $sClass = $this->_aModule['class_prefix'] . 'FormBroadcast';
        $oForm = new $sClass ();
        $oForm->initChecker();

        if ($oForm->isSubmittedAndValid ()) {
            
            $oEmailTemplate = new BxDolEmailTemplates();
            if (!$oEmailTemplate) {
                $this->_oTemplate->displayErrorOccured();
                return;
            }
            $aTemplate = $oEmailTemplate->getTemplate($this->_sPrefix . '_broadcast'); 
            $aTemplateVars = array (
                'BroadcastTitle' => $oForm->getCleanValue ('title'),
                'BroadcastMessage' => $oForm->getCleanValue ('message'),
                'EntryTitle' => $aDataEntry[$this->_oDb->_sFieldTitle],
                'EntryUrl' => BX_DOL_URL_ROOT . $this->_oConfig->getBaseUri() . 'view/' . $aDataEntry[$this->_oDb->_sFieldUri],                
            );
            $iSentMailsCounter = 0;            
            foreach ($aRecipients as $aProfile) {		        
       	        $iSentMailsCounter += sendMail($aProfile['Email'], $aTemplate['Subject'], $aTemplate['Body'], $aProfile['ID'], $aTemplateVars);
            
				$this->broadCastToInbox($aProfile, $aTemplate, $aTemplateVars);  
			}
            if (!$iSentMailsCounter) {
                $this->_oTemplate->displayErrorOccured();
                return;
            }

            echo MsgBox ($sMsgSent);

            $this->isAllowedBroadcast($aDataEntry, true); // perform send broadcast message action             
            $this->_oTemplate->addCss ('main.css');
            $this->_oTemplate->pageCode($sMsgSent, true, true);
            return;
        } 

        echo $oForm->getCode ();

        $this->_oTemplate->addCss ('main.css');
        $this->_oTemplate->pageCode($sTitle);
    }
 
    function _actionInvite ($iEntryId, $sEmailTemplate, $iMaxEmailInvitations, $sMsgInvitationSent, $sMsgNoUsers, $sTitle) {

		global $tmpl;
		require_once( BX_DIRECTORY_PATH_ROOT . 'templates/tmpl_' . $tmpl . '/scripts/BxTemplMailBox.php');
 

        $iEntryId = (int)$iEntryId;
        if (!($aDataEntry = $this->_oDb->getEntryByIdAndOwner($iEntryId, $this->_iProfileId, $this->isAdmin()))) {
            $this->_oTemplate->displayPageNotFound ();
            return;
        }

        $this->_oTemplate->pageStart();

        $GLOBALS['oTopMenu']->setCustomSubHeader($aDataEntry[$this->_oDb->_sFieldTitle]);
        $GLOBALS['oTopMenu']->setCustomVar($this->_sPrefix.'_view_uri', $aDataEntry[$this->_oDb->_sFieldUri]);
        
		if(!(($GLOBALS['site']['ver']=='7.0') && ($GLOBALS['site']['build']=='0'))) { 		
			$GLOBALS['oTopMenu']->setCustomBreadcrumbs(array(
				_t('_'.$this->_sPrefix) => BX_DOL_URL_ROOT . $this->_oConfig->getBaseUri() . 'home/',
				$aDataEntry[$this->_oDb->_sFieldTitle] => BX_DOL_URL_ROOT . $this->_oConfig->getBaseUri() . 'view/' . $aDataEntry[$this->_oDb->_sFieldUri],
				$sTitle . $aDataEntry[$this->_oDb->_sFieldTitle] => '',
			));
		}

        bx_import('BxDolTwigFormInviter');
        $oForm = new BxDolTwigFormInviter ($this, $sMsgNoUsers);
        $oForm->initChecker();

        if ($oForm->isSubmittedAndValid ()) {        

            $aInviter = getProfileInfo($this->_iProfileId);
            $aPlusOriginal = $this->_getInviteParams ($aDataEntry, $aInviter);
            
            $oEmailTemplate = new BxDolEmailTemplates();
            $aTemplate = $oEmailTemplate->getTemplate($sEmailTemplate);
            $iSuccess = 0;
			
			$sAcceptUrl = $aPlusOriginal['AcceptUrl'];

            // send invitation to registered members
            if (false !== bx_get('inviter_users') && is_array(bx_get('inviter_users'))) {
				$aInviteUsers = bx_get('inviter_users');
                foreach ($aInviteUsers as $iRecipient) {
                    $aRecipient = getProfileInfo($iRecipient);

 					$sInviteCode = $this->_oDb->addInvite($iEntryId, $iRecipient);
					$aPlusOriginal['AcceptUrl'] = $sAcceptUrl .'/'. $iRecipient .'/'. $sInviteCode; 

					$aPlus = array_merge (array ('NickName' => ' ' . $aRecipient['NickName']), $aPlusOriginal);
                    $iSuccess += sendMail(trim($aRecipient['Email']), $aTemplate['Subject'], $aTemplate['Body'], '', $aPlus) ? 1 : 0;
                 
					$this->inviteToInbox($aRecipient, $aTemplate, $aPlusOriginal);  
				}
            }

            // send invitation to additional emails
            $iMaxCount = $iMaxEmailInvitations;
            $aEmails = preg_split ("#[,\s\\b]+#", bx_get('inviter_emails'));
            $aPlus = array_merge (array ('NickName' => ''), $aPlusOriginal);
            if ($aEmails && is_array($aEmails)) {
                foreach ($aEmails as $sEmail) {
                    if (strlen($sEmail) < 5) 
                        continue;

 					$sInviteCode = $this->_oDb->addInvite($iEntryId, 0);
					$aPlus['AcceptUrl'] = $sAcceptUrl .'/0/'. $sInviteCode; 
 
                    $iRet = sendMail(trim($sEmail), $aTemplate['Subject'], $aTemplate['Body'], '', $aPlus) ? 1 : 0;
                    $iSuccess += $iRet;
                    if ($iRet && 0 == --$iMaxCount) 
                        break;
                }             
            }

            $sMsg = sprintf($sMsgInvitationSent, $iSuccess);
            echo MsgBox($sMsg);
            $this->_oTemplate->addCss ('main.css');
            $this->_oTemplate->pageCode ($sMsg, true, false);
            return;
        } 

        echo $oForm->getCode ();
        $this->_oTemplate->addCss ('main.css');
        $this->_oTemplate->addCss ('inviter.css');
        $this->_oTemplate->pageCode($sTitle . $aDataEntry[$this->_oDb->_sFieldTitle]);
    }
 
    function  inviteToInbox($aProfile, $aTemplate, $aPlusOriginal){
 
		$aMailBoxSettings = array
		(
			'member_id'	 =>  $this->_iProfileId, 
			'recipient_id'	 => $aProfile['ID'], 
			'messages_types'	 =>  'mail',  
		);
	
		$aComposeSettings = array
		(
			'send_copy' => false , 
			'send_copy_to_me' => false , 
			'notification' => false ,
		);
		$oMailBox = new BxTemplMailBox('mail_page', $aMailBoxSettings);
	
		$sMessageBody = $aTemplate['Body'];
		$sMessageBody = str_replace("<GroupName>", $aPlusOriginal['GroupName'] , $sMessageBody);
		$sMessageBody = str_replace("<GroupLocation>", $aPlusOriginal['GroupLocation'] , $sMessageBody);
		$sMessageBody = str_replace("<GroupUrl>", $aPlusOriginal['GroupUrl'] , $sMessageBody);
		$sMessageBody = str_replace("<AcceptUrl>", $aPlusOriginal['AcceptUrl'] .'/'. $aProfile['ID'] , $sMessageBody); 
		$sMessageBody = str_replace("<InviterUrl>", $aPlusOriginal['InviterUrl'] , $sMessageBody);
		$sMessageBody = str_replace("<InviterNickName>", $aPlusOriginal['InviterNickName'] , $sMessageBody);
		$sMessageBody = str_replace("<InvitationText>", $aPlusOriginal['InvitationText'] , $sMessageBody);
	
		$oMailBox -> sendMessage($aTemplate['Subject'], $sMessageBody, $aProfile['ID'], $aComposeSettings); 
	
   }

   function  broadCastToInbox($aProfile, $aTemplate, $aTemplateVars){
 
		$aMailBoxSettings = array
		(
			'member_id'	 =>  $this->_iProfileId, 
			'recipient_id'	 => $aProfile['ID'], 
			'messages_types'	 =>  'mail',  
		);
	
		$aComposeSettings = array
		(
			'send_copy' => false , 
			'send_copy_to_me' => false , 
			'notification' => false ,
		);
		$oMailBox = new BxTemplMailBox('mail_page', $aMailBoxSettings);
	
		$sMessageBody = $aTemplate['Body'];
		$sMessageBody = str_replace("<NickName>", getNickName($this->_iProfileId), $sMessageBody);
		$sMessageBody = str_replace("<EntryUrl>", $aTemplateVars['EntryUrl'], $sMessageBody);
		$sMessageBody = str_replace("<EntryTitle>", $aTemplateVars['EntryTitle'], $sMessageBody);
		$sMessageBody = str_replace("<BroadcastMessage>", $aTemplateVars['BroadcastMessage'], $sMessageBody);
	
		$oMailBox -> sendMessage($aTemplateVars['BroadcastTitle'], $sMessageBody, $aProfile['ID'], $aComposeSettings); 
	
    }

    function parseTags($s)
    {
        return $this->_parseAnything($s, ',', BX_DOL_URL_ROOT . $this->_oConfig->getBaseUri() . 'browse/tag/');
    }

    function parseCategories($s)
    {
        return $this->_parseAnything($s, CATEGORIES_DIVIDER, BX_DOL_URL_ROOT . $this->_oConfig->getBaseUri() . 'browse/category/');
    }

    function _parseAnything($s, $sDiv, $sLinkStart, $sClassName = '')
    {
        $sRet = '';
        $a = explode ($sDiv, $s);
        $sClass = $sClassName ? 'class="'.$sClassName.'"' : '';
        
        foreach ($a as $sName)
            $sRet .= '<a '.$sClass.' href="' . $sLinkStart . urlencode(title2uri($sName)) . '">'.$sName.'</a>&#160';
        
        return $sRet;
    } 

    function displayMainCalendar($iYear, $iMonth, $sTitle) {
    
        $this->_oTemplate->pageStart();
 
        bx_import ('Calendar', $this->_aModule);
        $oCalendar = bx_instance ($this->_aModule['class_prefix'] . 'Calendar', array ($iYear, $iMonth, $this->_oDb, $this->_oTemplate, $this->_oConfig));
  
        $aVars = array (
            'bx_repeat:week_names' => $oCalendar->_getWeekNames (),
            'bx_repeat:calendar_row' => $oCalendar->_getCalendar (),
            'month_prev_url' => $oCalendar->getBaseUri () . "{$oCalendar->iPrevYear}/{$oCalendar->iPrevMonth}&ajax=cal",
            'month_prev_name' => _t('_month_prev'),
            'month_prev_icon' => getTemplateIcon('sys_back.png'),
            'month_next_url' => $oCalendar->getBaseUri () . "{$oCalendar->iNextYear}/{$oCalendar->iNextMonth}&ajax=cal",
            'month_next_name' => _t('_month_next'),
            'month_next_icon' => getTemplateIcon('sys_next.png'),
            'month_current' => $oCalendar->getTitle(),
        );
        $sHtml = $this->_oTemplate->parseHtmlByName('main_calendar', $aVars);
        $sHtml = preg_replace ('#<bx_repeat:groups>.*?</bx_repeat:groups>#s', '', $sHtml);
        $this->_oTemplate->addCss('calendar.css');
        
	return $sHtml;
    } 

    function isMembershipEnabledForImages () {
        return ($this->_isMembershipEnabledFor ('BX_PHOTOS_ADD') && $this->_isMembershipEnabledFor ('BX_GROUPS_PHOTOS_ADD'));
    }

    function isMembershipEnabledForVideos () {
        return $this->_isMembershipEnabledFor ('BX_VIDEOS_ADD');
        return ($this->_isMembershipEnabledFor ('BX_VIDEOS_ADD') && $this->_isMembershipEnabledFor ('BX_GROUPS_VIDEOS_ADD')); 
    }

    function isMembershipEnabledForSounds () {
        return ($this->_isMembershipEnabledFor ('BX_SOUNDS_ADD') && $this->_isMembershipEnabledFor ('BX_SOUNDS_PHOTOS_ADD'));
    }

    function isMembershipEnabledForFiles () {
        return ($this->_isMembershipEnabledFor ('BX_FILES_ADD') && $this->_isMembershipEnabledFor ('BX_GROUPS_FILES_ADD'));
    }
 
    function _isMembershipEnabledFor ($sMembershipActionConstant) { 
        defineMembershipActions (array('photos add', 'sounds add', 'videos add', 'files add', 'groups photos add', 'groups sounds add', 'groups videos add', 'groups files add'));
		if (!defined($sMembershipActionConstant))
			return false;
		$aCheck = checkAction($_COOKIE['memberID'], constant($sMembershipActionConstant));
        return $aCheck[CHECK_ACTION_RESULT] == CHECK_ACTION_RESULT_ALLOWED;
    }  

    //[end] - ultimate groups mod from modzzz 
 

	/*[begin] map integration*/ 
    function actionMapEdit ($iEntryID) {

		$aDataEntry = $this->_oDb->getEntryById($iEntryID);
       
		$GLOBALS['oTopMenu']->setCustomSubHeader($aDataEntry[$this->_oDb->_sFieldTitle]);
        $GLOBALS['oTopMenu']->setCustomVar($this->_sPrefix.'_view_uri', $aDataEntry[$this->_oDb->_sFieldUri]);


        $aLocation = $iEntryID ? $this->_oDb->getProfileById($iEntryID) : false;
        if (!$iEntryID || !$this->isAllowedEditOwnLocation($iEntryID, $aLocation)) {
            $this->_oTemplate->displayAccessDenied ();
            return;
        } 
  
        if (!($aDataEntry = $this->_oDb->getEntryByIdAndOwner($iEntryID, $this->_iProfileId, $this->isAdmin()))) {
            $this->_oTemplate->displayPageNotFound ();
            return;
        }

        $this->_oTemplate->pageStart();
 
        bx_groups_import ('PageEdit');
        $oPage = new BxEventsPageEdit ($this, $aLocation);
        echo $oPage->getCode();

        $this->_oTemplate->addJs ('http://www.google.com/jsapi?key=' . getParam('bx_groups_key'));
        $this->_oTemplate->addJs ('BxMap.js');
        $this->_oTemplate->addCss ('main.css');
        $this->_oTemplate->addCss ('search.css');
        $this->_oTemplate->addCss ('map.css');
        $this->_oTemplate->pageCode(_t('_bx_groups_edit'), false, false);
    }  


    function actionSaveDataProfile ($iEntryID, $iZoom, $sMapType, $fLat, $fLng, $sMapClassInstanceName, $sAddress, $sCountry) {

        $aLocation = $iEntryID ? $this->_oDb->getProfileById($iEntryID) : false;
        if (!$iEntryID || !$this->isAllowedEditOwnLocation($iEntryID, $aLocation))
            return;


        if (!$aLocation && ('null' == $fLat || 'null' == $fLng))
            return;
        
        $fLat = 'null' != $fLat ? (float)$fLat : $aLocation['lat'];
        $fLng = 'null' != $fLng ? (float)$fLng : $aLocation['lng'];
        $iZoom = 'null' != $iZoom ? (int)$iZoom : ($aLocation ? $aLocation['zoom'] : -1);
        $sMapType = 'null' != $sMapType ? $sMapType : ($aLocation ? $aLocation['type'] : '');
        $sAddress = 'null' != $sAddress ? process_db_input($sAddress, BX_TAGS_STRIP) : '';
        $sCountry = 'null' != $sCountry ? process_db_input($sCountry, BX_TAGS_STRIP) : '';

        switch ($sMapType) {
            case 'normal':
            case 'satellite':
            case 'hybrid':
                break;
            default:
                $sMapType = 'normal';
        }

        if ($this->_oDb->insertProfileLocation ($this->_iProfileId,$iEntryID, $fLat, $fLng, $iZoom, $sMapType, $sAddress, $sCountry)) {
            $this->onEventProfileLocationManuallyUpdated ($iEntryID, array ('lat' => $fLat, 'lng' => $fLng, 'zoom' => $iZoom, 'map_type' => $sMapType, 'address' => $sAddress, 'country' => $sCountry));
            echo 1;
        }
    }
  
    function actionGetDataProfile ($iId, $sMapClassInstanceName) {
        
        $iProfileId = $iId;
        $r = $this->_oDb->getProfileById($iProfileId);
        if (!$r || !$this->isAllowedViewLocation ($iProfileId, $r))
            return;        

        if (!$iId) {
            $aRet = array ();
            $aRet[] = array (
                    'lat' => $r['lat'],
                    'lng' => $r['lng'],
                    'data' => '',
                    'icon' => array ('w' => 0, 'h' => 0, 'sw' => 0, 'sh' => 0, 'sd' => '', 'url' => ''),
                );

            $oParser = new Services_JSON();
            echo $oParser->encode($aRet);
            return;
        }

        $sImage = '';
        if ($r['thumb']) {
            $a = array ('ID' => $this->_oDb->getAuthorById($iId), 'Avatar' => $r['thumb']);
            $aImage = BxDolService::call('photos', 'get_image', array($a, 'browse'), 'Search');
            $sImage = $aImage['no_image'] ? '' : $aImage['file'];
        } 


        $aVars = array (
			 
			'bx_if:address1' => array( 
				'condition' =>  strlen(trim($r['address1'])),
				'content' => array(
					'address1' => trim($r['address1']), 
				) 
			), 
			'bx_if:address2' => array( 
				'condition' =>  strlen(trim($r['address2'])),
				'content' => array(
					'address2' => trim($r['address2']), 
				) 
			),  
			'thumb' => $sImage ? $sImage : $this->_oTemplate->getIconUrl('no-photo.png'), 
			'url_flag' => genFlagUrl($r['country']),
			'country' => _t($GLOBALS['aPreValues']['Country'][$r['country']]['LKey']),
			'city' => trim($r['city']) ? $r['city'] : _t('_bx_groups_unknown_city'), 
		);
        $sHtml = $this->_oTemplate->parseHtmlByName ('popup_profile', $aVars);

        $aIconJSON = false;
        /*
		if ($r['thumb']) {

			include_once (BX_DIRECTORY_PATH_MODULES . 'boonex/avatar/include.php');
	        $sAvatarImg = BX_AVA_URL_USER_AVATARS . $r['Avatar'] . BX_AVA_EXT;
            $aIconJSON = array ('w' => 32, 'h' => 32, 'sw' => 34, 'sh' => 34, 'sd' => '1', 'url' => $sAvatarImg);
        }
		*/
        if (!$aIconJSON) {
            $sIconUser = $this->_oTemplate->getIconUrl ('user.png');
            $aIconJSON = array ('w' => 16, 'h' => 16, 'sw' => 24, 'sh' => 16, 'sd' => '', 'url' => $sIconUser);
        }

        $aRet = array ();
        $aRet[] = array (
                'lat' => $r['lat'],
                'lng' => $r['lng'],
                'data' => $sHtml,
                'icon' => $aIconJSON, 
            );

        $oParser = new Services_JSON();
        echo $oParser->encode($aRet);        
    }

    function actionGetHtmlProfiles ($sFilter) {        

        $aProfiles = $this->_getProfilesByFilter ($sFilter);
        if (!$aProfiles) {
            echo MsgBox(_t('_Empty'));
            return;
        }

        if (!$aProfiles) {
            echo MsgBox(_t('_Empty'));
            return;
        }

        bx_import ('BxTemplSearchProfile');
        $oBxTemplSearchProfile = new BxTemplSearchProfile();
        foreach ($aProfiles as $r) {
            $aProfileInfo = $this->_oDb->getProfileInfo($r['id']);
            $sProfiles .= $oBxTemplSearchProfile->displaySearchUnit($aProfileInfo);
        }

        echo $GLOBALS['oFunctions']->centerContent($sProfiles, '.searchrow_block_simple');
    }

    function actionGetData ($iZoom, $fLatMin, $fLatMax, $fLngMin, $fLngMax, $sMapClassInstanceName, $sFilter = '') {

        $fLatMin = (float)$fLatMin;
        $fLatMax = (float)$fLatMax;
        $fLngMin = (float)$fLngMin;
        $fLngMax = (float)$fLngMax;

        if ($sFilter) {
            echo $this->_getProfilesData('filter', $sFilter, 0, 0);
            return;
        }

        $iZoom = (int)$iZoom;
        if ($iZoom >= BX_GROUPS_ZOOM_COUNTRIES && $iZoom < BX_GROUPS_ZOOM_CITIES) {
            echo $this->_getCountriesData($fLatMin, $fLatMax, $fLngMin, $fLngMax, $sMapClassInstanceName);
        } elseif ($iZoom >= BX_GROUPS_ZOOM_CITIES && $iZoom < BX_GROUPS_ZOOM_PROFILES) {
            echo $this->_getCitiesData($fLatMin, $fLatMax, $fLngMin, $fLngMax, $sMapClassInstanceName);
        } elseif ($iZoom >= BX_GROUPS_ZOOM_PROFILES) {
            echo $this->_getProfilesData($fLatMin, $fLatMax, $fLngMin, $fLngMax);
        }
    }

    function _getProfilesData ($fLatMin, $fLatMax, $fLngMin, $fLngMax) {

        $sIconUser = $this->_oTemplate->getIconUrl ('user.png');
        $sIconGroup = $this->_oTemplate->getIconUrl ('group.png');

        if ('filter' == $fLatMin) {
            $a = $this->_getProfilesByFilter ($fLatMax); 
        } else {
            $a = $this->_oDb->getProfilesByBounds((float)$fLatMin, (float)$fLatMax, (float)$fLngMin, (float)$fLngMax);
        }

        $aa = array ();
        foreach ($a as $r) {
            $sKey = $r['lat'].'x'.$r['lng'];
            $aVars = array ('thumb' => get_member_thumbnail($r['id'], 'none', true));
            $aa[$sKey][] = array (
                'lat' => $r['lat'],
                'lng' => $r['lng'],
                'username' => $r['NickName'],
                'html' => $this->_oTemplate->parseHtmlByName ('popup_profile', $aVars),
            );
        }

        $aRet = array();
        foreach ($aa as $k => $a) {
            $sHtml = '';
            $aUsernames = array ();
            foreach ($a as $r) {
                $sHtml .= $r['html'];
                $aUsernames[] = $r['username'];
            }
            $aVars = array ('content' => $sHtml);
            $aRet[] = array (
                'lat' => $r['lat'],
                'lng' => $r['lng'],                
                'usernames' => $aUsernames,
                'data' => $this->_oTemplate->parseHtmlByName ('popup_profiles', $aVars),                
                'icon' => array ('w' => 16, 'h' => 16, 'sw' => 24, 'sh' => 16, 'sd' => '', 'url' => (count($a) > 1 ? $sIconGroup : $sIconUser)),
            );
        }
        $oParser = new Services_JSON();
        return $oParser->encode($aRet);
    }

    function _getCitiesData ($fLatMin, $fLatMax, $fLngMin, $fLngMax, $sMapClassInstanceName) {

        $sIconUrl = $this->_oTemplate->getIconUrl ('city.png');

        $a = $this->_oDb->getCitiesByBounds((float)$fLatMin, (float)$fLatMax, (float)$fLngMin, (float)$fLngMax);

        if (!preg_match('/^[A-Za-z0-9]+$/', $sMapClassInstanceName))
            return '';        

        $aRet = array();
        foreach ($a as $r) {
            $aVars = array (
                'url_flag' => genFlagUrl($r['country']),
                'country' => _t($GLOBALS['aPreValues']['Country'][$r['country']]['LKey']),
                'city' => trim($r['city']) ? $r['city'] : _t('_bx_groups_unknown_city'),
                'num' => sprintf(_t('_bx_groups_%d_members'), $r['num']),
                'lat' => $r['lat'],
                'lng' => $r['lng'],
                'zoom' => BX_GROUPS_ZOOM_PROFILES,
                'map_instance_name' => $sMapClassInstanceName,
            );
            $sHtml = $this->_oTemplate->parseHtmlByName ('popup_city', $aVars);
            $aRet[] = array (
                'lat' => $r['lat'],
                'lng' => $r['lng'],
                'data' => $sHtml,
                'icon' => array ('w' => 48, 'h' => 28, 'sw' => 72, 'sh' => 48, 'sd' => '', 'url' => $sIconUrl),
            );
        }
        $oParser = new Services_JSON();
        return $oParser->encode($aRet);
    }

    function _getCountriesData ($fLatMin, $fLatMax, $fLngMin, $fLngMax, $sMapClassInstanceName) {

        $a = $this->_oDb->getCountriesByBounds((float)$fLatMin, (float)$fLatMax, (float)$fLngMin, (float)$fLngMax);

        if (!preg_match('/^[A-Za-z0-9]+$/', $sMapClassInstanceName))
            return '';

        $aRet = array();
        foreach ($a as $r) {
            $sFlagUrl = genFlagUrl($r['country']);
            $aVars = array (
                'url_flag' => $sFlagUrl, 
                'country' => _t($GLOBALS['aPreValues']['Country'][$r['country']]['LKey']), 
                'num' => sprintf(_t('_bx_groups_%d_members'), $r['num']),
                'lat' => $r['lat'],
                'lng' => $r['lng'],
                'zoom' => BX_GROUPS_ZOOM_CITIES,
                'map_instance_name' => $sMapClassInstanceName,
            );
            $sHtml = $this->_oTemplate->parseHtmlByName ('popup_country', $aVars);
            $aRet[] = array (
                'lat' => $r['lat'],
                'lng' => $r['lng'],
                'data' => $sHtml,
                'icon' => array ('w' => 18, 'h' => 12, 'sw' => 20, 'sh' => 14, 'sd' => 1, 'url' => $sFlagUrl),
            );
        }
        $oParser = new Services_JSON();
        return $oParser->encode($aRet);
    }

    // ================================== admin actions

    function actionClearTable ($sTable,  $isClearFailedOnly = true) {

        if (!$this->isAdmin()) {
            $this->_oTemplate->displayAccessDenied ();
            return;
        }

        switch ($sTable) {
            case 'countries':
                $this->_oDb->clearCountries ($isClearFailedOnly ? true : false);
                $this->_oTemplate->displayMsg('Countries locations has been cleared');
                break;
            case 'cities':
                $this->_oDb->clearCities ($isClearFailedOnly ? true : false);
                $this->_oTemplate->displayMsg('Cities locations has been cleared');
                break;
            default:
                $this->_oTemplate->displayPageNotFound ();
        }
    }

    function actionUpdateCountries ($iLimit = 4, $iDelay = 6) { 

        if (!$this->isAdmin()) {
            $this->_oTemplate->displayAccessDenied ();
            return;            
        }

        $iLimit = (int)$iLimit;
        $iDelay = (int)$iDelay;

        $a = $this->_oDb->getUndefinedCountries ($iLimit);
        if ($a) {
            foreach ($a as $sCountryCode => $sCountryName) {
                $a = $this->_geocode ($sCountryName, $sCountryCode);                                
                if ($a) {                                        
                    $this->_oDb->insertCountryLocation ($sCountryCode, $a[0], $a[1]);
                } else {
                    $this->_oDb->insertCountryLocation ($sCountryCode, 0, 0, 1);
                }
                $this->onEventGeolocateCountry ($sCountryCode, array ('lat' => (isset($a[0]) ? $a[0] : false), 'lng' => (isset($a[1]) ? $a[1] : false)));
                if ($iDelay)
                    sleep ($iDelay);
            }

            $aVars = array (
                'refresh' => 1,
                'msg' => 'Countries update is in progress, please wait...',
            );
            echo $this->_oTemplate->parseHtmlByName ('updating', $aVars);
        } else {
            $this->_oTemplate->displayMsg('Countries locations update has been completed');
        }
    }

    function actionUpdateCities ($iLimit = 4, $iDelay = 6) {

        if (!$this->isAdmin()) {
            $this->_oTemplate->displayAccessDenied ();
            return;            
        }

        $iLimit = (int)$iLimit;
        $iDelay = (int)$iDelay;

        $a = $this->_oDb->getUndefinedCities ($iLimit);
        if ($a) {

            foreach ($a as $sCountryCode => $sCity) {
                $this->_updateCityLocation($iDelay, $sCity, $sCountryCode);
            }

            $aVars = array (
                'refresh' => 1,
                'msg' => 'Cities update is in progress, please wait...',
            );
            echo $this->_oTemplate->parseHtmlByName ('updating', $aVars);
        } else {
            $this->_oTemplate->displayMsg('Cities locations update has been completed');
        }
    }

    function actionUpdateProfiles ($iLimit = 4, $iDelay = 6) {

        if (!$this->isAdmin()) {
            $this->_oTemplate->displayAccessDenied ();
            return;            
        }

        $iLimit = (int)$iLimit;
        $iDelay = (int)$iDelay;

        $a = $this->_oDb->getUndefinedProfiles ($iLimit);
        if ($a) {
            foreach ($a as $iId => $r) {
                $this->_updateProfileLocation ($iDelay, $r);
            }

            $aVars = array (
                'refresh' => 1,
                'msg' => 'Listings update is in progress, please wait...',
            );
            echo $this->_oTemplate->parseHtmlByName ('updating', $aVars);
        } else {
            $this->_oTemplate->displayMsg('Listings locations update has been completed');
        }
    }
  
    function onEventGeolocateProfile ($iProfileId, $aLocation) {
		//
    }

    function onEventGeolocateCity ($sCity, $aLocation) {
		//
    }

    function onEventGeolocateCountry ($sCountryCode, $aLocation) {
		//
    }

    function onEventProfileLocationManuallyUpdated ($iProfileId, $aLocation) {
		//
    }
 
    // ================================== service actions

    /**
     * Get profile location by user id
     * @param $iProfileId user's id 
     * @param $iViewerProfileId viewer profile id
     * @param $isClearFailedOnly check privacy settings before returning location
     * @return array with location info on success, false on error, -1 if access denied
     */ 
    function serviceGetLocation ($iProfileId, $iViewerProfileId = 0, $isCheckPrivacy = true) {
        $iProfileId = (int)$iProfileId;
        $iViewerProfileId = (int)$iViewerProfileId;
        if ($isCheckPrivacy) {
            if (!$iViewerProfileId)
                $iViewerProfileId = $this->_iProfileId; 
            if (!$this->_oPrivacy->check('view_location', $iProfileId, $iViewerProfileId))
                return -1;
        }

        $aLocation = $iProfileId ? $this->_oDb->getProfileById($iProfileId) : false;
        if (!$aLocation)
            return false;

        if (-1 == $aLocation['zoom'])
            $aLocation['zoom'] = getParam('bx_groups_profile_zoom');

        if (!$aLocation['type'])
            $aLocation['type'] = getParam('bx_groups_profile_map_type');

        return $aLocation;
    }

    /**
     * Edit location block
     * @param $iEntryId user's id which location is edited
     * @return html with clickable map
     */ 
    function serviceEditLocation ($iEntryId) {

        $iEntryId = (int)$iEntryId;

        $aLocation = $iEntryId ? $this->_oDb->getProfileById($iEntryId) : false;
        if (!$aLocation)
            return false;
 
        $fLat = false;
        $fLng = false;
        $iZoom = false;
        $sMapType = false;

        if ($aLocation) {
            $fLat = $aLocation['lat'];
            $fLng = $aLocation['lng'];
            $iZoom = $aLocation['zoom'];
            $sMapType = $aLocation['type'];
        }

        if (false === $fLat || false === $fLng) {
            $aProfile = $this->_oDb->getProfileInfo($iEntryId);
            $aLocationCountry = $this->_oDb->getCountryByCode($aProfile['country'], false);
            $fLat = $aLocationCountry['lat'];
            $fLng = $aLocationCountry['lng'];
            $iZoom = BX_GROUPS_ZOOM_CITIES;            
        }

        if (false === $iZoom || -1 == $iZoom)
            $iZoom = 5;

        if (!$sMapType)
            $sMapType = 'normal';

        $aVars = array (
            'msg_incorrect_google_key' => _t('_bx_groups_msg_incorrect_google_key'),
            'loading' => _t('_loading ...'),
            'map_control' => 'small',
            'map_is_type_control' => 1 ,
            'map_is_scale_control' => 0,
            'map_is_overview_control' => 0,
            'map_is_dragable' => 1 , 
			'map_type' => $sMapType,
            'map_lat' => $fLat,
            'map_lng' => $fLng,
            'map_zoom' => $iZoom,
            'suffix' => 'Edit',
            'subclass' => 'bx_groups_profile',
            'data_url' => BX_DOL_URL_MODULES . "?r=groups/get_data_profile/0/{instance}/{ts}",
            'save_data_url' => BX_DOL_URL_MODULES . "?r=groups/save_data_profile/{$iEntryId}/{zoom}/{map_type}/{lat}/{lng}/{instance}/{address}/{country}/{ts}",
            'save_location_url' => '',
            'shadow_url' => '',
        );
        return  $this->_oTemplate->parseHtmlByName('map', $aVars);
    }
  

    /**
     * Removes any geocoding information associated with profile
     * @param $iProfileId user's id which location going to be removed
     * @return true if location existed and was deleted, false on error or location didn't exist
     */ 
    function serviceDeleteProfileLocation ($iProfileId) {
        return $this->_oDb->deleteLocation((int)$iProfileId);
    }

    /**
     * Update profile's location
     * @param $iProfileId user's id which location going to be removed
     * @return true if position was successfully geocoded, and false if doesn't
     */     
    function serviceUpdateProfileLocation ($iProfileId) {
        $iProfileId = (int)$iProfileId;
        $a = $this->_oDb->getProfileInfo($iProfileId);
        if ($this->_updateProfileLocation(0, $a)) {
            if (!$this->_oDb->isCityLocationExists($a['country'], process_db_input($a['city'], BX_TAGS_NO_ACTION, BX_SLASHES_NO_ACTION)))
                $this->_updateCityLocation(0, $a['city'], $a['country']);
            return true;
        }
        return false;
    }

    /**
     * Update profile's location manually
     * @param $iProfileId user's id which location going to be updated 
     * @param $fLat latitude
     * @param $gLng longitude
     * @param $iZoom zoom level
     * @param $sMapType map type (hybrid, satellite or standard)
     * @param $sCountry 2 letters country code
     * @param $sAddress address string
     * @return true if position was successfully updated, and false if doesn't
     */     
    function serviceUpdateProfileLocationManually ($iEntryId, $fLat, $fLng, $iZoom, $sMapType, $sCountry, $sAddress) {
        $a = $this->_oDb->getProfileInfo((int)$iEntryId);
        $aLocationOld = $this->_oDb->getProfileById((int)$iEntryId);

        if (!$iZoom)
            $iZoom = $aLocationOld && $aLocationOld['zoom'] ? $aLocationOld['zoom'] : -1;
        switch ($sMapType) {
        case 'hybrid':
        case 'satellite':
        case 'standard':
        break;
        default:
            $sMapType = 'standard'; 
        }

        $fLat = (float)$fLat;
        $fLng = (float)$fLng;
        $iZoom = (int)$iZoom;

        $iRet = $this->_oDb->insertProfileLocation (
			$this->_iProfileId,    
			$iEntryId, 
            $fLat, 
            $fLng, 
            $iZoom, 
            $sMapType, 
            '', // address 
            '', // country 
            $aLocationOld && $aLocationOld['allow_view_location_to'] ? $aLocationOld['allow_view_location_to'] : BX_GROUPS_DEFAULT_PRIVACY);

        if ($iRet) {
            $this->onEventProfileLocationManuallyUpdated ($iEntryId, array ('lat' => $fLat, 'lng' => $fLng, 'zoom' => $iZoom, 'map_type' => $sMapType, 'address' => '', 'country' => ''));
            return true;
        }

        return false;
    }
 
 
    // ================================== permissions  

    function isAllowedEditOwnLocation ($iEntryID, &$aLocation) {
        if(!$iEntryID) 
            return false;
        if (!$aLocation || $aLocation['id'] == $iEntryID) {
            return true;
        }        
        return false;
    }

    function isAllowedViewLocation ($iEntryID, &$aLocation) {
        if (!$aLocation) 
            return false;
		
		$aDataEntry = $this->_oDb->getEntryById($iEntryID);
 
        if ($aDataEntry['author_id'] == $this->_iProfileId || $this->isAdmin())
            return true;
 
        return $this->_oMapPrivacy->check('view_location', $iEntryID, $this->_iProfileId);  
    }
  
    function isAdmin () {
        return $GLOBALS['logged']['admin'] || $GLOBALS['logged']['moderator'];
    }             

    // ================================== other 

    function _geocode ($sAddress, $sCountryCode = '') {

        $iRet = 404;

        $sAddress = rawurlencode($sAddress);
        $sUrl = "http://maps.google.com/maps/geo";

        $s = bx_file_get_contents($sUrl, array(
            'q' => $sAddress,
            'output' => 'xml',
            'key' => getParam('bx_groups_key')
        ));
        
        if (preg_match ('/<code>(\d+)<\/code>/', $s, $m))
        {
            $iRet = $m[1];
            if (200 != $iRet) return false;

            if (preg_match_all ('/<CountryNameCode>([A-Za-z]+)<\/CountryNameCode>/', $s, $mCountry) &&
                preg_match_all ('/<coordinates>([0-9,\.-]+)<\/coordinates>/', $s, $mCoord))
            {
                if (isset($mCountry[1]) && is_array($mCountry[1]))
                    $mCountry = $mCountry[1];

                foreach ($mCountry AS $k => $v)
                {
                    if (!$sCountryCode || ($sCountryCode && 0 == strcasecmp($sCountryCode, $v))) 
                    {
                        // Parse coordinate string
                        list ($fLongitude, $fLatitude, $fAltitude) = explode(",", $mCoord[1][$k]);
                        return array ($fLatitude, $fLongitude, $v);
                    }
                }
            }
        }
        return false;
    }

    function _updateCityLocation($iDelay, &$sCity, $sCountryCode) {

        $iDelay = (int)$iDelay;
        if ($iDelay) sleep ($iDelay);
        $a = $this->_geocode ($sCity . ' ' . $sCountryCode, $sCountryCode);        
        if ($a) {
            $this->_oDb->insertCityLocation ($sCountryCode, process_db_input($sCity, BX_TAGS_NO_ACTION, BX_SLASHES_NO_ACTION), $a[0], $a[1]);
            $bRet = true;
        } else {
            $this->_oDb->insertCityLocation ($sCountryCode, process_db_input($sCity, BX_TAGS_NO_ACTION, BX_SLASHES_NO_ACTION), 0, 0, 1);
            $bRet = false;
        }
        $this->onEventGeolocateCity ($sCity, array ('lat' => (isset($a[0]) ? $a[0] : false), 'lng' => (isset($a[1]) ? $a[1] : false), 'country' => $sCountryCode));
        return $bRet;
    }

    function _updateProfileLocation($iDelay, &$r) {

        $iDelay = (int)$iDelay;

        $iId = (int)$r['id'];
        $a = false;

		$sState = (($r['country']=='US') && $r['state']) ? $r['state'] : '';

        if (isset ($r['city'])) { 
            if ($iDelay) sleep ($iDelay);
 
			if($sState)
				$a = $this->_geocode ($r['city'] . ' ' . $sState . ' ' . $r['country'], $r['country']);
			else
				$a = $this->_geocode ($r['city'] . ' ' . $r['country'], $r['country']);  
        }

        if (!$a && isset ($r['zip'])) { 
            if ($iDelay) sleep ($iDelay);
            $a = $this->_geocode ($r['zip'] . ' ' . $r['country'], $r['country']); 
        }

        if (!$a) { 
            if ($iDelay) sleep ($iDelay);
 
			if($sState)
				$a = $this->_geocode ($r['city'] . ' ' . $sState . ' ' . $r['country'], $r['country']);
			else
				$a = $this->_geocode ($r['city'] . ' ' . $r['country'], $r['country']);
        }
      
        if ($a) {
            $this->_oDb->insertProfileLocation ($r['author_id'], $iId, $a[0], $a[1], -1, '', process_db_input($r['city'] . ', ' . $r['country'], BX_TAGS_NO_ACTION, BX_SLASHES_NO_ACTION), process_db_input($r['country'], BX_TAGS_NO_ACTION, BX_SLASHES_NO_ACTION), BX_GROUPS_DEFAULT_PRIVACY);
            $bRet = true;
        } else {
            $this->_oDb->insertProfileLocation ($r['author_id'], $iId, 0, 0, -1, '', '', '', BX_GROUPS_DEFAULT_PRIVACY, 1);
            $bRet = false;
        }          
        $this->onEventGeolocateProfile ($iId, array ('lat' => (isset($a[0]) ? $a[0] : false), 'lng' => (isset($a[1]) ? $a[1] : false), 'country' => $sCountryCode));
        return $bRet;
    }

    function _saveLocationByPrefix ($sPrefix, $iZoom, $sMapType, $fLat, $fLng) {

        if (!$this->isAdmin()) {
            echo 'Access denied';
            return;
        }

        if ($iZoom = (int)$iZoom)
            setParam($sPrefix . '_zoom', $iZoom);

        switch ($sMapType) {
            case 'normal':
            case 'satellite':
            case 'hybrid':
                setParam($sPrefix . '_map_type', $sMapType);
        }                

        if ($fLat = (float)$fLat)
            setParam($sPrefix . '_lat', $fLat);

        if ($fLng = (float)$fLng)
            setParam($sPrefix . '_lng', $fLng);

        echo 'ok';
    }    

    function _saveLocationForm ($sSuffix, $sMap) {

        if (!preg_match('/^[A-Za-z0-9]+$/', $sSuffix))
            return '';

        $aCustomForm = array(
            
            'form_attrs' => array(
                'name'     => "bx_groups_save_location_{$sSuffix}",
                'onsubmit'   => "return glBxMap{$sSuffix}.saveLocation();",
                'method'   => 'post',
            ),

            'inputs' => array(

                'Map' => array (
                    'type' => 'custom',
                    'content' => "<div class=\"bx_groups_form_map\">$sMap</div>",
                    'name' => 'Map',
                    'caption' => _t('_bx_groups_admin_map'),
                ),

                'Submit' => array (
                    'type' => 'submit',
                    'name' => 'submit_form',
                    'value' => _t('_bx_groups_admin_save_location'),
                    'colspan' => true,
                ),                            
            ),
        );

        $f = new BxTemplFormView ($aCustomForm);
        return $f->getCode();
    }

    function _getProfilesByFilter ($sFilter) {

        $aGetParams = unserialize(base64_decode($sFilter));            
        if ($aGetParams && is_array($aGetParams))
            $aGetParams = $_REQUEST = $_GET = array_merge ($_REQUEST, $aGetParams);

        bx_import('BxDolProfileFields');
        $oPF = new BxDolProfileFields(9);
        $aRequestParams = $oPF->collectSearchRequestParams();

        bx_import ('BxTemplProfileView');
        $oProfileGenerator = new BxBaseProfileGenerator((int)$_COOKIE['memberID']);
        list ($aWhere, $sJoin, $sPossibleOrder) = $oProfileGenerator->GenSqlConditions($oPF->aBlocks, $aRequestParams);

        $iPage = isset($aGetParams['page']) && (int)$aGetParams['page'] > 0 ? (int)$aGetParams['page'] : 1;
        $iPerPage = isset($aGetParams['per_page']) && (int)$aGetParams['per_page'] > 0 ? (int)$aGetParams['per_page'] : getParam('bx_groups_per_page'); 
        $iStart = ($iPage - 1) * $iPerPage;            
        
        $sQuery = 'SELECT DISTINCT `' . $this->_oDb->_sPrefix . 'main`.`id`, `' . $this->_oDb->_sPrefix . 'main`.`thumb`, `' . $this->_oDb->_sPrefix . 'main`.`title` as `NickName`, `m`.`id`, `m`.`lat`, `m`.`lng`
            FROM `' . $this->_oDb->_sPrefix . 'main` 
            INNER JOIN `' . $this->_oDb->_sPrefix . 'profiles` AS `m` ON (`' . $this->_oDb->_sPrefix . 'main` .`id` = `m`.`id`) 
            ' . $sJoin . ' 
            WHERE ' . implode( ' AND ', $aWhere ) . ' AND `m`.`failed` = 0 ' . $sPossibleOrder . " 
            LIMIT $iStart, $iPerPage";

        // ID is ambiguous
        $sQuery = str_replace (' `id`', ' `' . $this->_oDb->_sPrefix . 'main`.`id`', $sQuery);
        
        $aProfiles = $GLOBALS['MySQL']->getAll($sQuery);

        return $aProfiles;
    } 
	/*[end] map integration*/


	/******[BEGIN] Sponsor functions **************************/ 
    function actionSponsor ($sAction, $sSponsorIdUri) {
		switch($sAction){
			case 'add': 
				$this->actionSponsorAdd ($sSponsorIdUri, '_bx_groups_page_title_sponsor_add');
			break;
			case 'edit':
				$this->actionSponsorEdit ($sSponsorIdUri, '_bx_groups_page_title_sponsor_edit');
			break;
			case 'delete':
				$this->actionSponsorDelete ($sSponsorIdUri, _t('_bx_groups_msg_location_was_sponsor_deleted'));
			break;
			case 'view':
				$this->actionSponsorView ($sSponsorIdUri, _t('_bx_groups_msg_pending_sponsor_approval')); 
			break; 
			case 'browse':
				return $this->actionSponsorBrowse ($sSponsorIdUri, '_bx_groups_page_title_sponsor_browse'); 
			break;  
		}
	}
    
    function actionSponsorBrowse ($sUri, $sTitle) {
       
        if (!($aDataEntry = $this->_oDb->getEntryByUri($sUri))) {
            $this->_oTemplate->displayPageNotFound ();
            return;
        }		
		
		$this->_oTemplate->pageStart();

        $GLOBALS['oTopMenu']->setCustomSubHeader($aDataEntry[$this->_oDb->_sFieldTitle]);
        $GLOBALS['oTopMenu']->setCustomVar($this->_sPrefix.'_view_uri', $aDataEntry[$this->_oDb->_sFieldUri]);

        bx_import ('SponsorPageBrowse', $this->_aModule);
        $sClass = $this->_aModule['class_prefix'] . 'SponsorPageBrowse';
        $oPage = new $sClass ($this, $sUri);
        echo $oPage->getCode();
        $this->_oTemplate->addCss ('main.css');
        $this->_oTemplate->addCss ('unit.css');
        $this->_oTemplate->pageCode(_t($sTitle, $aDataEntry[$this->_oDb->_sFieldTitle]), false, false);  
    }
 
    function actionSponsorView ($sUri, $sMsgPendingApproval) {

		$aSponsorEntry = $this->_oDb->getSponsorEntryByUri($sUri);
		$iEntryId = (int)$aSponsorEntry['group_id'];
 
        if (!($aDataEntry = $this->_oDb->getEntryById($iEntryId))) {
            $this->_oTemplate->displayPageNotFound ();
            return;
        }
 
        $this->_oTemplate->pageStart();
 
        $GLOBALS['oTopMenu']->setCustomSubHeader($aDataEntry[$this->_oDb->_sFieldTitle] .' - '. $aSponsorEntry[$this->_oDb->_sFieldTitle]);
        $GLOBALS['oTopMenu']->setCustomVar($this->_sPrefix.'_view_uri', $aDataEntry[$this->_oDb->_sFieldUri]);


        bx_import ('SponsorPageView', $this->_aModule);
        $sClass = $this->_aModule['class_prefix'] . 'SponsorPageView';
        $oPage = new $sClass ($this, $aSponsorEntry);

        if ($aDataEntry[$this->_oDb->_sFieldStatus] == 'pending') {
            $aVars = array ('msg' => $sMsgPendingApproval); // this product is pending approval, please wait until it will be activated
            echo $this->_oTemplate->parseHtmlByName ('pending_approval_plank', $aVars);
        }

        echo $oPage->getCode();

        bx_import('SponsorCmts', $this->_aModule);
        $sClass = $this->_aModule['class_prefix'] . 'SponsorCmts';
        $oCmts = new $sClass ($this->_sPrefix, 0);

        $this->_oTemplate->setPageDescription (substr(strip_tags($aSponsorEntry['desc']), 0, 255));
 
        $this->_oTemplate->addCss ('view.css');
        $this->_oTemplate->addCss ('main.css');
        $this->_oTemplate->addCss ('entry_view.css');
        $this->_oTemplate->pageCode($aSponsorEntry['title'], false, false); 
    }


    function actionSponsorEdit ($iEntryId, $sTitle) { 

        $iEntryId = (int)$iEntryId;

		$aSponsorEntry = $this->_oDb->getSponsorEntryById($iEntryId);
		$iSponsorId = (int)$aSponsorEntry['group_id'];
  
        if (!($aDataEntry = $this->_oDb->getEntryById($iSponsorId))) {
            $this->_oTemplate->displayPageNotFound ();
            return;
        }
  
        if (!$this->isAllowedEdit($aDataEntry)) {
            $this->_oTemplate->displayAccessDenied ();
            return;
        }

        $this->_oTemplate->pageStart();
 
        $GLOBALS['oTopMenu']->setCustomSubHeader($aDataEntry[$this->_oDb->_sFieldTitle]);
        $GLOBALS['oTopMenu']->setCustomVar($this->_sPrefix.'_view_uri', $aDataEntry[$this->_oDb->_sFieldUri]);
		 
        bx_import ('SponsorFormEdit', $this->_aModule);
        $sClass = $this->_aModule['class_prefix'] . 'SponsorFormEdit';
        $oForm = new $sClass ($this, $aSponsorEntry['uri'], $iSponsorId,  $iEntryId, $aSponsorEntry);
  
        $oForm->initChecker($aSponsorEntry);

        if ($oForm->isSubmittedAndValid ()) {
 
            $this->_oDb->_sTableMain = 'sponsor_main';
			$this->_oDb->_sFieldId = 'id';
			$this->_oDb->_sFieldUri = 'uri';
			$this->_oDb->_sFieldTitle = 'title';
			$this->_oDb->_sFieldDescription = 'desc'; 
			$this->_oDb->_sFieldThumb = 'thumb';
			$this->_oDb->_sFieldStatus = 'status'; 
			$this->_oDb->_sFieldCreated = 'created';
 
			$this->_oDb->_sTableMediaPrefix = $this->_oDb->_sTableSponsorMediaPrefix;
 
            if ($oForm->update ($iEntryId, $aValsAdd)) {
  
				$oForm->processMedia($iEntryId, $this->_iProfileId);
  
                $this->isAllowedEdit($aDataEntry, true); // perform action
 
                header ('Location:' . BX_DOL_URL_ROOT . $this->_oConfig->getBaseUri() . 'sponsor/view/' . $aSponsorEntry['uri']);
                exit;

            } else {

                echo MsgBox(_t('_Error Occured'));
                
            }            

        } else {

            echo $oForm->getCode ();

        }

        $this->_oTemplate->addJs ('main.js');
        $this->_oTemplate->addCss ('main.css');
        $this->_oTemplate->addCss ('forms_extra.css');
        $this->_oTemplate->pageCode(_t($sTitle, $aSponsorEntry['title']));  
    }

    function actionSponsorDelete ($iSponsorId, $sMsgSuccess) {

		$aSponsorEntry = $this->_oDb->getSponsorEntryById($iSponsorId);
		$iEntryId = (int)$aSponsorEntry['group_id'];
  
        if (!($aDataEntry = $this->_oDb->getEntryByIdAndOwner($iEntryId, $this->_iProfileId, $this->isAdmin()))) {
            echo MsgBox(_t('_sys_request_page_not_found_cpt')) . genAjaxyPopupJS($iEntryId, 'ajaxy_popup_result_div');
            exit;
        }

        if (!$this->isAllowedDelete($aDataEntry) || 0 != strcasecmp($_SERVER['REQUEST_METHOD'], 'POST')) {
            echo MsgBox(_t('_Access denied')) . genAjaxyPopupJS($iEntryId, 'ajaxy_popup_result_div');
            exit;
        }

        if ($this->_oDb->deleteSponsorByIdAndOwner($iSponsorId, $iEntryId, $this->_iProfileId, $this->isAdmin())) {
            $this->isAllowedDelete($aDataEntry, true); // perform action
            $this->onEventSponsorDeleted ($iEntryId, $aDataEntry);            
            $sRedirect = BX_DOL_URL_ROOT . $this->_oConfig->getBaseUri() . 'view/' . $aDataEntry['uri'];
  
            $sJQueryJS = genAjaxyPopupJS($iEntryId, 'ajaxy_popup_result_div', $sRedirect);
            echo MsgBox(_t($sMsgSuccess)) . $sJQueryJS;
            exit;
        }

        echo MsgBox(_t('_Error Occured')) . genAjaxyPopupJS($iEntryId, 'ajaxy_popup_result_div');
        exit;
    }
 
    function actionSponsorAdd ($iSponsorId, $sTitle) {
  
        if (!$this->isAllowedAdd()) {
            $this->_oTemplate->displayAccessDenied ();
            return;
        }
 
		if (!($aDataEntry = $this->_oDb->getEntryById($iSponsorId))) {
			$this->_oTemplate->displayPageNotFound ();
			return;
		}	

        $this->_oTemplate->pageStart();

        $GLOBALS['oTopMenu']->setCustomSubHeader($aDataEntry[$this->_oDb->_sFieldTitle]);
        $GLOBALS['oTopMenu']->setCustomVar($this->_sPrefix.'_view_uri', $aDataEntry[$this->_oDb->_sFieldUri]);
		 
        $this->_addSponsorForm($iSponsorId);

        $this->_oTemplate->addJs ('main.js');
        $this->_oTemplate->addCss ('main.css');
        $this->_oTemplate->addCss ('forms_extra.css');
        $this->_oTemplate->pageCode(_t($sTitle, $aDataEntry[$this->_oDb->_sFieldTitle]));  
    }
 
    function _addSponsorForm ($iSponsorId) { 
 
        bx_import ('SponsorFormAdd', $this->_aModule);
        $sClass = $this->_aModule['class_prefix'] . 'SponsorFormAdd';
        $oForm = new $sClass ($this, $this->_iProfileId, $iSponsorId);
        $oForm->initChecker();

        if ($oForm->isSubmittedAndValid ()) {
 
			$sStatus = 'approved';

            $this->_oDb->_sTableMain = 'sponsor_main';
			$this->_oDb->_sFieldId = 'id';
			$this->_oDb->_sFieldUri = 'uri';
			$this->_oDb->_sFieldTitle = 'title';
			$this->_oDb->_sFieldDescription = 'desc'; 
			$this->_oDb->_sFieldThumb = 'thumb';
			$this->_oDb->_sFieldStatus = 'status'; 
			$this->_oDb->_sFieldCreated = 'created';
 
			$this->_oDb->_sTableMediaPrefix = $this->_oDb->_sTableSponsorMediaPrefix;
 
            $aValsAdd = array (
                $this->_oDb->_sFieldCreated => time(),
                $this->_oDb->_sFieldUri => $oForm->generateUri(),
                $this->_oDb->_sFieldStatus => $sStatus,
            );                        
 
            $iEntryId = $oForm->insert ($aValsAdd);
 
            if ($iEntryId) {

                $this->isAllowedAdd(true); // perform action                 
 
				$oForm->processMedia($iEntryId, $this->_iProfileId); 
	  
                $aDataEntry = $this->_oDb->getSponsorEntryById($iEntryId);
    
				$sRedirectUrl = BX_DOL_URL_ROOT . $this->_oConfig->getBaseUri() . 'sponsor/view/' . $aDataEntry[$this->_oDb->_sFieldUri];
			  
                header ('Location:' . $sRedirectUrl);
                exit;

            } else {

                MsgBox(_t('_Error Occured'));
            }
                         
        } else { 
            echo $oForm->getCode (); 
        }
    }
 

    function onEventSponsorDeleted ($iEntryId, $aDataEntry = array()) {

        // delete associated tags and categories 
        $this->reparseSponsorTags ($iEntryId);
        $this->reparseSponsorCategories ($iEntryId);

        // delete votings
        bx_import('SponsorVoting', $this->_aModule);
        $sClass = $this->_aModule['class_prefix'] . 'SponsorVoting';
        $oVoting = new $sClass ($this->_oDb->_sSponsorPrefix, 0, 0);
        $oVoting->deleteVotings ($iEntryId);

        // delete comments 
        bx_import('SponsorCmts', $this->_aModule);
        $sClass = $this->_aModule['class_prefix'] . 'SponsorCmts';
        $oCmts = new $sClass ($this->_oDb->_sSponsorPrefix, $iEntryId);
        $oCmts->onObjectDelete ();

        // delete views
        bx_import ('BxDolViews');
        $oViews = new BxDolViews($this->_oDb->_sSponsorPrefix, $iEntryId, false);
        $oViews->onObjectDelete();

 
        // arise alert
		//$oAlert = new BxDolAlerts($this->_sPrefix, 'delete', $iEntryId, $this->_iProfileId);
		//$oAlert->alert();
    }        


    /*******[END - Sponsor Functions] ******************************/


	/******[BEGIN] Venue functions **************************/ 
    function actionVenue ($sAction, $sVenueIdUri) {
		switch($sAction){
			case 'add': 
				$this->actionVenueAdd ($sVenueIdUri, '_bx_groups_page_title_venue_add');
			break;
			case 'edit':
				$this->actionVenueEdit ($sVenueIdUri, '_bx_groups_page_title_venue_edit');
			break;
			case 'delete':
				$this->actionVenueDelete ($sVenueIdUri, _t('_bx_groups_msg_location_was_venue_deleted'));
			break;
			case 'view':
				$this->actionVenueView ($sVenueIdUri, _t('_bx_groups_msg_pending_venue_approval')); 
			break; 
			case 'browse':
				return $this->actionVenueBrowse ($sVenueIdUri, '_bx_groups_page_title_venue_browse'); 
			break;  
		}
	}
    
    function actionVenueBrowse ($sUri, $sTitle) {
       
        if (!($aDataEntry = $this->_oDb->getEntryByUri($sUri))) {
            $this->_oTemplate->displayPageNotFound ();
            return;
        }		
		
		$this->_oTemplate->pageStart();

        $GLOBALS['oTopMenu']->setCustomSubHeader($aDataEntry[$this->_oDb->_sFieldTitle]);
        $GLOBALS['oTopMenu']->setCustomVar($this->_sPrefix.'_view_uri', $aDataEntry[$this->_oDb->_sFieldUri]);

        bx_import ('VenuePageBrowse', $this->_aModule);
        $sClass = $this->_aModule['class_prefix'] . 'VenuePageBrowse';
        $oPage = new $sClass ($this, $sUri);
        echo $oPage->getCode();
        $this->_oTemplate->addCss ('main.css');
        $this->_oTemplate->addCss ('unit.css');
        $this->_oTemplate->pageCode(_t($sTitle, $aDataEntry[$this->_oDb->_sFieldTitle]), false, false);  
    }
 
    function actionVenueView ($sUri, $sMsgPendingApproval) {

		$aVenueEntry = $this->_oDb->getVenueEntryByUri($sUri);
		$iEntryId = (int)$aVenueEntry['group_id'];
 
        if (!($aDataEntry = $this->_oDb->getEntryById($iEntryId))) {
            $this->_oTemplate->displayPageNotFound ();
            return;
        }
 
        $this->_oTemplate->pageStart();
 
        $GLOBALS['oTopMenu']->setCustomSubHeader($aDataEntry[$this->_oDb->_sFieldTitle] .' - '. $aVenueEntry[$this->_oDb->_sFieldTitle]);
        $GLOBALS['oTopMenu']->setCustomVar($this->_sPrefix.'_view_uri', $aDataEntry[$this->_oDb->_sFieldUri]);


        bx_import ('VenuePageView', $this->_aModule);
        $sClass = $this->_aModule['class_prefix'] . 'VenuePageView';
        $oPage = new $sClass ($this, $aVenueEntry);

        if ($aDataEntry[$this->_oDb->_sFieldStatus] == 'pending') {
            $aVars = array ('msg' => $sMsgPendingApproval); // this product is pending approval, please wait until it will be activated
            echo $this->_oTemplate->parseHtmlByName ('pending_approval_plank', $aVars);
        }

        echo $oPage->getCode();

        bx_import('VenueCmts', $this->_aModule);
        $sClass = $this->_aModule['class_prefix'] . 'VenueCmts';
        $oCmts = new $sClass ($this->_sPrefix, 0);

        $this->_oTemplate->setPageDescription (substr(strip_tags($aVenueEntry['desc']), 0, 255));
 
        $this->_oTemplate->addCss ('view.css');
        $this->_oTemplate->addCss ('main.css');
        $this->_oTemplate->addCss ('entry_view.css');
        $this->_oTemplate->pageCode($aVenueEntry['title'], false, false); 
    }


    function actionVenueEdit ($iEntryId, $sTitle) { 

        $iEntryId = (int)$iEntryId;

		$aVenueEntry = $this->_oDb->getVenueEntryById($iEntryId);
		$iVenueId = (int)$aVenueEntry['group_id'];
  
        if (!($aDataEntry = $this->_oDb->getEntryById($iVenueId))) {
            $this->_oTemplate->displayPageNotFound ();
            return;
        }
  
        if (!$this->isAllowedEdit($aDataEntry)) {
            $this->_oTemplate->displayAccessDenied ();
            return;
        }

        $this->_oTemplate->pageStart();
 
        $GLOBALS['oTopMenu']->setCustomSubHeader($aDataEntry[$this->_oDb->_sFieldTitle]);
        $GLOBALS['oTopMenu']->setCustomVar($this->_sPrefix.'_view_uri', $aDataEntry[$this->_oDb->_sFieldUri]);
		 
        bx_import ('VenueFormEdit', $this->_aModule);
        $sClass = $this->_aModule['class_prefix'] . 'VenueFormEdit';
        $oForm = new $sClass ($this, $aVenueEntry['uri'], $iVenueId,  $iEntryId, $aVenueEntry);
  
        $oForm->initChecker($aVenueEntry);

        if ($oForm->isSubmittedAndValid ()) {
 
            $this->_oDb->_sTableMain = 'venue_main';
			$this->_oDb->_sFieldId = 'id';
			$this->_oDb->_sFieldUri = 'uri';
			$this->_oDb->_sFieldTitle = 'title';
			$this->_oDb->_sFieldDescription = 'desc'; 
			$this->_oDb->_sFieldThumb = 'thumb';
			$this->_oDb->_sFieldStatus = 'status'; 
			$this->_oDb->_sFieldCreated = 'created';
 
			$this->_oDb->_sTableMediaPrefix = $this->_oDb->_sTableVenueMediaPrefix;
 
            if ($oForm->update ($iEntryId, $aValsAdd)) {
  
				$oForm->processMedia($iEntryId, $this->_iProfileId);
  
                $this->isAllowedEdit($aDataEntry, true); // perform action
 
                header ('Location:' . BX_DOL_URL_ROOT . $this->_oConfig->getBaseUri() . 'venue/view/' . $aVenueEntry['uri']);
                exit;

            } else {

                echo MsgBox(_t('_Error Occured'));
                
            }            

        } else {

            echo $oForm->getCode ();

        }

        $this->_oTemplate->addJs ('main.js');
        $this->_oTemplate->addCss ('main.css');
        $this->_oTemplate->addCss ('forms_extra.css');
        $this->_oTemplate->pageCode(_t($sTitle, $aVenueEntry['title']));  
    }

    function actionVenueDelete ($iVenueId, $sMsgSuccess) {

		$aVenueEntry = $this->_oDb->getVenueEntryById($iVenueId);
		$iEntryId = (int)$aVenueEntry['group_id'];
  
        if (!($aDataEntry = $this->_oDb->getEntryByIdAndOwner($iEntryId, $this->_iProfileId, $this->isAdmin()))) {
            echo MsgBox(_t('_sys_request_page_not_found_cpt')) . genAjaxyPopupJS($iEntryId, 'ajaxy_popup_result_div');
            exit;
        }

        if (!$this->isAllowedDelete($aDataEntry) || 0 != strcasecmp($_SERVER['REQUEST_METHOD'], 'POST')) {
            echo MsgBox(_t('_Access denied')) . genAjaxyPopupJS($iEntryId, 'ajaxy_popup_result_div');
            exit;
        }

        if ($this->_oDb->deleteVenueByIdAndOwner($iVenueId, $iEntryId, $this->_iProfileId, $this->isAdmin())) {
            $this->isAllowedDelete($aDataEntry, true); // perform action
            $this->onEventVenueDeleted ($iEntryId, $aDataEntry);            
            $sRedirect = BX_DOL_URL_ROOT . $this->_oConfig->getBaseUri() . 'view/' . $aDataEntry['uri'];
  
            $sJQueryJS = genAjaxyPopupJS($iEntryId, 'ajaxy_popup_result_div', $sRedirect);
            echo MsgBox(_t($sMsgSuccess)) . $sJQueryJS;
            exit;
        }

        echo MsgBox(_t('_Error Occured')) . genAjaxyPopupJS($iEntryId, 'ajaxy_popup_result_div');
        exit;
    }
 
    function actionVenueAdd ($iVenueId, $sTitle) {
  
        if (!$this->isAllowedAdd()) {
            $this->_oTemplate->displayAccessDenied ();
            return;
        }
 
		if (!($aDataEntry = $this->_oDb->getEntryById($iVenueId))) {
			$this->_oTemplate->displayPageNotFound ();
			return;
		}	

        $this->_oTemplate->pageStart();

        $GLOBALS['oTopMenu']->setCustomSubHeader($aDataEntry[$this->_oDb->_sFieldTitle]);
        $GLOBALS['oTopMenu']->setCustomVar($this->_sPrefix.'_view_uri', $aDataEntry[$this->_oDb->_sFieldUri]);
		 
        $this->_addVenueForm($iVenueId);

        $this->_oTemplate->addJs ('main.js');
        $this->_oTemplate->addCss ('main.css');
        $this->_oTemplate->addCss ('forms_extra.css');
        $this->_oTemplate->pageCode(_t($sTitle, $aDataEntry[$this->_oDb->_sFieldTitle]));  
    }
 
    function _addVenueForm ($iVenueId) { 
 
        bx_import ('VenueFormAdd', $this->_aModule);
        $sClass = $this->_aModule['class_prefix'] . 'VenueFormAdd';
        $oForm = new $sClass ($this, $this->_iProfileId, $iVenueId);
        $oForm->initChecker();

        if ($oForm->isSubmittedAndValid ()) {
 
			$sStatus = 'approved';

            $this->_oDb->_sTableMain = 'venue_main';
			$this->_oDb->_sFieldId = 'id';
			$this->_oDb->_sFieldUri = 'uri';
			$this->_oDb->_sFieldTitle = 'title';
			$this->_oDb->_sFieldDescription = 'desc'; 
			$this->_oDb->_sFieldThumb = 'thumb';
			$this->_oDb->_sFieldStatus = 'status'; 
			$this->_oDb->_sFieldCreated = 'created';
 
			$this->_oDb->_sTableMediaPrefix = $this->_oDb->_sTableVenueMediaPrefix;
 
            $aValsAdd = array (
                $this->_oDb->_sFieldCreated => time(),
                $this->_oDb->_sFieldUri => $oForm->generateUri(),
                $this->_oDb->_sFieldStatus => $sStatus,
            );                        
 
            $iEntryId = $oForm->insert ($aValsAdd);
 
            if ($iEntryId) {

                $this->isAllowedAdd(true); // perform action                 
 
				$oForm->processMedia($iEntryId, $this->_iProfileId); 
	  
                $aDataEntry = $this->_oDb->getVenueEntryById($iEntryId);
    
				$sRedirectUrl = BX_DOL_URL_ROOT . $this->_oConfig->getBaseUri() . 'venue/view/' . $aDataEntry[$this->_oDb->_sFieldUri];
			  
                header ('Location:' . $sRedirectUrl);
                exit;

            } else {

                MsgBox(_t('_Error Occured'));
            }
                         
        } else { 
            echo $oForm->getCode (); 
        }
    }
 

    function onEventVenueDeleted ($iEntryId, $aDataEntry = array()) {

        // delete associated tags and categories 
        $this->reparseVenueTags ($iEntryId);
        $this->reparseVenueCategories ($iEntryId);

        // delete votings
        bx_import('VenueVoting', $this->_aModule);
        $sClass = $this->_aModule['class_prefix'] . 'VenueVoting';
        $oVoting = new $sClass ($this->_oDb->_sVenuePrefix, 0, 0);
        $oVoting->deleteVotings ($iEntryId);

        // delete comments 
        bx_import('VenueCmts', $this->_aModule);
        $sClass = $this->_aModule['class_prefix'] . 'VenueCmts';
        $oCmts = new $sClass ($this->_oDb->_sVenuePrefix, $iEntryId);
        $oCmts->onObjectDelete ();

        // delete views
        bx_import ('BxDolViews');
        $oViews = new BxDolViews($this->_oDb->_sVenuePrefix, $iEntryId, false);
        $oViews->onObjectDelete();

 
        // arise alert
		//$oAlert = new BxDolAlerts($this->_sPrefix, 'delete', $iEntryId, $this->_iProfileId);
		//$oAlert->alert();
    }        


    /*******[END - VENUE Functions] ******************************/


	/******[BEGIN] News functions **************************/ 
    function actionNews ($sAction, $sNewsIdUri) {
		switch($sAction){
			case 'add': 
				$this->actionNewsAdd ($sNewsIdUri, '_bx_groups_page_title_news_add');
			break;
			case 'edit':
				$this->actionNewsEdit ($sNewsIdUri, '_bx_groups_page_title_news_edit');
			break;
			case 'delete':
				$this->actionNewsDelete ($sNewsIdUri, _t('_bx_groups_msg_location_was_news_deleted'));
			break;
			case 'view':
				$this->actionNewsView ($sNewsIdUri, _t('_bx_groups_msg_pending_news_approval')); 
			break; 
			case 'browse':
				return $this->actionNewsBrowse ($sNewsIdUri, '_bx_groups_page_title_news_browse'); 
			break;  
		}
	}
    
    function actionNewsBrowse ($sUri, $sTitle) {
       
        if (!($aDataEntry = $this->_oDb->getEntryByUri($sUri))) {
            $this->_oTemplate->displayPageNotFound ();
            return;
        }		
		
		$this->_oTemplate->pageStart();

        $GLOBALS['oTopMenu']->setCustomSubHeader($aDataEntry[$this->_oDb->_sFieldTitle]);
        $GLOBALS['oTopMenu']->setCustomVar($this->_sPrefix.'_view_uri', $aDataEntry[$this->_oDb->_sFieldUri]);

        bx_import ('NewsPageBrowse', $this->_aModule);
        $sClass = $this->_aModule['class_prefix'] . 'NewsPageBrowse';
        $oPage = new $sClass ($this, $sUri);
        echo $oPage->getCode();
        $this->_oTemplate->addCss ('main.css');
        $this->_oTemplate->addCss ('unit.css');
        $this->_oTemplate->pageCode(_t($sTitle, $aDataEntry[$this->_oDb->_sFieldTitle]), false, false);  
    }
 
    function actionNewsView ($sUri, $sMsgPendingApproval) {

		$aNewsEntry = $this->_oDb->getNewsEntryByUri($sUri);
		$iEntryId = (int)$aNewsEntry['group_id'];
 
        if (!($aDataEntry = $this->_oDb->getEntryById($iEntryId))) {
            $this->_oTemplate->displayPageNotFound ();
            return;
        }
 
        $this->_oTemplate->pageStart();
 
        $GLOBALS['oTopMenu']->setCustomSubHeader($aDataEntry[$this->_oDb->_sFieldTitle] .' - '. $aNewsEntry[$this->_oDb->_sFieldTitle]);
        $GLOBALS['oTopMenu']->setCustomVar($this->_sPrefix.'_view_uri', $aDataEntry[$this->_oDb->_sFieldUri]);


        bx_import ('NewsPageView', $this->_aModule);
        $sClass = $this->_aModule['class_prefix'] . 'NewsPageView';
        $oPage = new $sClass ($this, $aNewsEntry);

        if ($aDataEntry[$this->_oDb->_sFieldStatus] == 'pending') {
            $aVars = array ('msg' => $sMsgPendingApproval); // this product is pending approval, please wait until it will be activated
            echo $this->_oTemplate->parseHtmlByName ('pending_approval_plank', $aVars);
        }

        echo $oPage->getCode();

        bx_import('NewsCmts', $this->_aModule);
        $sClass = $this->_aModule['class_prefix'] . 'NewsCmts';
        $oCmts = new $sClass ($this->_sPrefix, 0);

        $this->_oTemplate->setPageDescription (substr(strip_tags($aNewsEntry['desc']), 0, 255));
 
        $this->_oTemplate->addCss ('view.css');
        $this->_oTemplate->addCss ('main.css');
        $this->_oTemplate->addCss ('entry_view.css');
        $this->_oTemplate->pageCode($aNewsEntry['title'], false, false); 
    }


    function actionNewsEdit ($iEntryId, $sTitle) { 

        $iEntryId = (int)$iEntryId;

		$aNewsEntry = $this->_oDb->getNewsEntryById($iEntryId);
		$iNewsId = (int)$aNewsEntry['group_id'];
  
        if (!($aDataEntry = $this->_oDb->getEntryById($iNewsId))) {
            $this->_oTemplate->displayPageNotFound ();
            return;
        }
  
        if (!$this->isAllowedEdit($aDataEntry)) {
            $this->_oTemplate->displayAccessDenied ();
            return;
        }

        $this->_oTemplate->pageStart();
 
        $GLOBALS['oTopMenu']->setCustomSubHeader($aDataEntry[$this->_oDb->_sFieldTitle]);
        $GLOBALS['oTopMenu']->setCustomVar($this->_sPrefix.'_view_uri', $aDataEntry[$this->_oDb->_sFieldUri]);
		 
        bx_import ('NewsFormEdit', $this->_aModule);
        $sClass = $this->_aModule['class_prefix'] . 'NewsFormEdit';
        $oForm = new $sClass ($this, $aNewsEntry['uri'], $iNewsId,  $iEntryId, $aNewsEntry);
  
        $oForm->initChecker($aNewsEntry);

        if ($oForm->isSubmittedAndValid ()) {
 
            $this->_oDb->_sTableMain = 'news_main';
			$this->_oDb->_sFieldId = 'id';
			$this->_oDb->_sFieldUri = 'uri';
			$this->_oDb->_sFieldTitle = 'title';
			$this->_oDb->_sFieldDescription = 'desc'; 
			$this->_oDb->_sFieldThumb = 'thumb';
			$this->_oDb->_sFieldStatus = 'status'; 
			$this->_oDb->_sFieldCreated = 'created';
 
			$this->_oDb->_sTableMediaPrefix = $this->_oDb->_sTableNewsMediaPrefix;
 
            if ($oForm->update ($iEntryId, $aValsAdd)) {
  
				$oForm->processMedia($iEntryId, $this->_iProfileId);
  
                $this->isAllowedEdit($aDataEntry, true); // perform action
 
                header ('Location:' . BX_DOL_URL_ROOT . $this->_oConfig->getBaseUri() . 'news/view/' . $aNewsEntry['uri']);
                exit;

            } else {

                echo MsgBox(_t('_Error Occured'));
                
            }            

        } else {

            echo $oForm->getCode ();

        }

        $this->_oTemplate->addJs ('main.js');
        $this->_oTemplate->addCss ('main.css');
        $this->_oTemplate->addCss ('forms_extra.css');
        $this->_oTemplate->pageCode(_t($sTitle, $aNewsEntry['title']));  
    }

    function actionNewsDelete ($iNewsId, $sMsgSuccess) {

		$aNewsEntry = $this->_oDb->getNewsEntryById($iNewsId);
		$iEntryId = (int)$aNewsEntry['group_id'];
  
        if (!($aDataEntry = $this->_oDb->getEntryByIdAndOwner($iEntryId, $this->_iProfileId, $this->isAdmin()))) {
            echo MsgBox(_t('_sys_request_page_not_found_cpt')) . genAjaxyPopupJS($iEntryId, 'ajaxy_popup_result_div');
            exit;
        }

        if (!$this->isAllowedDelete($aDataEntry) || 0 != strcasecmp($_SERVER['REQUEST_METHOD'], 'POST')) {
            echo MsgBox(_t('_Access denied')) . genAjaxyPopupJS($iEntryId, 'ajaxy_popup_result_div');
            exit;
        }

        if ($this->_oDb->deleteNewsByIdAndOwner($iNewsId, $iEntryId, $this->_iProfileId, $this->isAdmin())) {
            $this->isAllowedDelete($aDataEntry, true); // perform action
            $this->onEventNewsDeleted ($iEntryId, $aDataEntry);            
            $sRedirect = BX_DOL_URL_ROOT . $this->_oConfig->getBaseUri() . 'view/' . $aDataEntry['uri'];
  
            $sJQueryJS = genAjaxyPopupJS($iEntryId, 'ajaxy_popup_result_div', $sRedirect);
            echo MsgBox(_t($sMsgSuccess)) . $sJQueryJS;
            exit;
        }

        echo MsgBox(_t('_Error Occured')) . genAjaxyPopupJS($iEntryId, 'ajaxy_popup_result_div');
        exit;
    }
 
    function actionNewsAdd ($iNewsId, $sTitle) {
  
        if (!$this->isAllowedAdd()) {
            $this->_oTemplate->displayAccessDenied ();
            return;
        }
 
		if (!($aDataEntry = $this->_oDb->getEntryById($iNewsId))) {
			$this->_oTemplate->displayPageNotFound ();
			return;
		}	

        $this->_oTemplate->pageStart();

        $GLOBALS['oTopMenu']->setCustomSubHeader($aDataEntry[$this->_oDb->_sFieldTitle]);
        $GLOBALS['oTopMenu']->setCustomVar($this->_sPrefix.'_view_uri', $aDataEntry[$this->_oDb->_sFieldUri]);
		 
        $this->_addNewsForm($iNewsId);

        $this->_oTemplate->addJs ('main.js');
        $this->_oTemplate->addCss ('main.css');
        $this->_oTemplate->addCss ('forms_extra.css');
        $this->_oTemplate->pageCode(_t($sTitle, $aDataEntry[$this->_oDb->_sFieldTitle]));  
    }
 
    function _addNewsForm ($iNewsId) { 
 
        bx_import ('NewsFormAdd', $this->_aModule);
        $sClass = $this->_aModule['class_prefix'] . 'NewsFormAdd';
        $oForm = new $sClass ($this, $this->_iProfileId, $iNewsId);
        $oForm->initChecker();

        if ($oForm->isSubmittedAndValid ()) {
 
			$sStatus = 'approved';

            $this->_oDb->_sTableMain = 'news_main';
			$this->_oDb->_sFieldId = 'id';
			$this->_oDb->_sFieldUri = 'uri';
			$this->_oDb->_sFieldTitle = 'title';
			$this->_oDb->_sFieldDescription = 'desc'; 
			$this->_oDb->_sFieldThumb = 'thumb';
			$this->_oDb->_sFieldStatus = 'status'; 
			$this->_oDb->_sFieldCreated = 'created';
 
			$this->_oDb->_sTableMediaPrefix = $this->_oDb->_sTableNewsMediaPrefix;
 
            $aValsAdd = array (
                $this->_oDb->_sFieldCreated => time(),
                $this->_oDb->_sFieldUri => $oForm->generateUri(),
                $this->_oDb->_sFieldStatus => $sStatus,
            );                        
 
            $iEntryId = $oForm->insert ($aValsAdd);
 
            if ($iEntryId) {

                $this->isAllowedAdd(true); // perform action                 
 
				$oForm->processMedia($iEntryId, $this->_iProfileId); 
	  
                $aDataEntry = $this->_oDb->getNewsEntryById($iEntryId);
    
				$sRedirectUrl = BX_DOL_URL_ROOT . $this->_oConfig->getBaseUri() . 'news/view/' . $aDataEntry[$this->_oDb->_sFieldUri];
			  
                header ('Location:' . $sRedirectUrl);
                exit;

            } else {

                MsgBox(_t('_Error Occured'));
            }
                         
        } else { 
            echo $oForm->getCode (); 
        }
    }
 

    function onEventNewsDeleted ($iEntryId, $aDataEntry = array()) {

        // delete associated tags and categories 
        $this->reparseNewsTags ($iEntryId);
        $this->reparseNewsCategories ($iEntryId);

        // delete votings
        bx_import('NewsVoting', $this->_aModule);
        $sClass = $this->_aModule['class_prefix'] . 'NewsVoting';
        $oVoting = new $sClass ($this->_oDb->_sNewsPrefix, 0, 0);
        $oVoting->deleteVotings ($iEntryId);

        // delete comments 
        bx_import('NewsCmts', $this->_aModule);
        $sClass = $this->_aModule['class_prefix'] . 'NewsCmts';
        $oCmts = new $sClass ($this->_oDb->_sNewsPrefix, $iEntryId);
        $oCmts->onObjectDelete ();

        // delete views
        bx_import ('BxDolViews');
        $oViews = new BxDolViews($this->_oDb->_sNewsPrefix, $iEntryId, false);
        $oViews->onObjectDelete();

 
        // arise alert
		//$oAlert = new BxDolAlerts($this->_sPrefix, 'delete', $iEntryId, $this->_iProfileId);
		//$oAlert->alert();
    }        


    /*******[END - News Functions] ******************************/



	/******[BEGIN] Event functions **************************/ 
    function actionEvent ($sAction, $sGroupIdUri) {
		switch($sAction){
			case 'add': 
				$this->actionEventAdd ($sGroupIdUri, '_bx_groups_page_title_event_add');
			break;
			case 'edit':
				$this->actionEventEdit ($sGroupIdUri, '_bx_groups_page_title_event_edit');
			break;
			case 'delete':
				$this->actionEventDelete ($sGroupIdUri, _t('_bx_groups_msg_location_was_event_deleted'));
			break;
			case 'view':
				$this->actionEventView ($sGroupIdUri, _t('_bx_groups_msg_pending_event_approval')); 
			break; 
			case 'browse':
				return $this->actionEventBrowse ($sGroupIdUri, '_bx_groups_page_title_event_browse'); 
			break;  
		}
	}
    
    function actionEventBrowse ($sUri, $sTitle) {
       
        if (!($aDataEntry = $this->_oDb->getEntryByUri($sUri))) {
            $this->_oTemplate->displayPageNotFound ();
            return;
        }		
		
		$this->_oTemplate->pageStart();

        $GLOBALS['oTopMenu']->setCustomSubHeader($aDataEntry[$this->_oDb->_sFieldTitle]);
        $GLOBALS['oTopMenu']->setCustomVar($this->_sPrefix.'_view_uri', $aDataEntry[$this->_oDb->_sFieldUri]);

        bx_import ('EventPageBrowse', $this->_aModule);
        $sClass = $this->_aModule['class_prefix'] . 'EventPageBrowse';
        $oPage = new $sClass ($this, $sUri);
        echo $oPage->getCode();
        $this->_oTemplate->addCss ('main.css');
        $this->_oTemplate->addCss ('unit.css');
        $this->_oTemplate->pageCode(_t($sTitle, $aDataEntry[$this->_oDb->_sFieldTitle]), false, false);  
    }
 
    function actionEventView ($sUri, $sMsgPendingApproval) {

		$aEventEntry = $this->_oDb->getEventEntryByUri($sUri);
		$iEntryId = (int)$aEventEntry['group_id'];
 
        if (!($aDataEntry = $this->_oDb->getEntryById($iEntryId))) {
            $this->_oTemplate->displayPageNotFound ();
            return;
        }
 
        $this->_oTemplate->pageStart();
 
        $GLOBALS['oTopMenu']->setCustomSubHeader($aDataEntry[$this->_oDb->_sFieldTitle] .' - '. $aEventEntry[$this->_oDb->_sFieldTitle]);
        $GLOBALS['oTopMenu']->setCustomVar($this->_sPrefix.'_view_uri', $aDataEntry[$this->_oDb->_sFieldUri]);


        bx_import ('EventPageView', $this->_aModule);
        $sClass = $this->_aModule['class_prefix'] . 'EventPageView';
        $oPage = new $sClass ($this, $aEventEntry);

        if ($aDataEntry[$this->_oDb->_sFieldStatus] == 'pending') {
            $aVars = array ('msg' => $sMsgPendingApproval); // this product is pending approval, please wait until it will be activated
            echo $this->_oTemplate->parseHtmlByName ('pending_approval_plank', $aVars);
        }

        echo $oPage->getCode();

        bx_import('EventCmts', $this->_aModule);
        $sClass = $this->_aModule['class_prefix'] . 'EventCmts';
        $oCmts = new $sClass ($this->_sPrefix, 0);

        $this->_oTemplate->setPageDescription (substr(strip_tags($aEventEntry['desc']), 0, 255));
 
        $this->_oTemplate->addCss ('view.css');
        $this->_oTemplate->addCss ('main.css');
        $this->_oTemplate->addCss ('entry_view.css');
        $this->_oTemplate->pageCode($aEventEntry['title'], false, false); 
    }


    function actionEventEdit ($iEntryId, $sTitle) { 

        $iEntryId = (int)$iEntryId;

		$aEventEntry = $this->_oDb->getEventEntryById($iEntryId);
		$iGroupId = (int)$aEventEntry['group_id'];
  
        if (!($aDataEntry = $this->_oDb->getEntryById($iGroupId))) {
            $this->_oTemplate->displayPageNotFound ();
            return;
        }
  
        if (!$this->isAllowedEdit($aDataEntry)) {
            $this->_oTemplate->displayAccessDenied ();
            return;
        }

        $this->_oTemplate->pageStart();
 
        $GLOBALS['oTopMenu']->setCustomSubHeader($aDataEntry[$this->_oDb->_sFieldTitle]);
        $GLOBALS['oTopMenu']->setCustomVar($this->_sPrefix.'_view_uri', $aDataEntry[$this->_oDb->_sFieldUri]);
		 
        bx_import ('EventFormEdit', $this->_aModule);
        $sClass = $this->_aModule['class_prefix'] . 'EventFormEdit';
        $oForm = new $sClass ($this, $aEventEntry['uri'], $iGroupId,  $iEntryId, $aEventEntry);
  
        $oForm->initChecker($aEventEntry);

        if ($oForm->isSubmittedAndValid ()) {
 
            $this->_oDb->_sTableMain = 'event_main';
			$this->_oDb->_sFieldId = 'id';
			$this->_oDb->_sFieldUri = 'uri';
			$this->_oDb->_sFieldTitle = 'title';
			$this->_oDb->_sFieldDescription = 'desc'; 
			$this->_oDb->_sFieldThumb = 'thumb';
			$this->_oDb->_sFieldStatus = 'status'; 
			$this->_oDb->_sFieldCreated = 'created';
 
			$this->_oDb->_sTableMediaPrefix = $this->_oDb->_sTableEventMediaPrefix;
 
            if ($oForm->update ($iEntryId, $aValsAdd)) {
  
				$oForm->processMedia($iEntryId, $this->_iProfileId);
  
                $this->isAllowedEdit($aDataEntry, true); // perform action
 
                header ('Location:' . BX_DOL_URL_ROOT . $this->_oConfig->getBaseUri() . 'event/view/' . $aEventEntry['uri']);
                exit;

            } else {

                echo MsgBox(_t('_Error Occured'));
                
            }            

        } else {

            echo $oForm->getCode ();

        }

        $this->_oTemplate->addJs ('main.js');
        $this->_oTemplate->addCss ('main.css');
        $this->_oTemplate->addCss ('forms_extra.css');
        $this->_oTemplate->pageCode(_t($sTitle, $aEventEntry['title']));  
    }

    function actionEventDelete ($iGroupId, $sMsgSuccess) {

		$aEventEntry = $this->_oDb->getEventEntryById($iGroupId);
		$iEntryId = (int)$aEventEntry['group_id'];
  
        if (!($aDataEntry = $this->_oDb->getEntryByIdAndOwner($iEntryId, $this->_iProfileId, $this->isAdmin()))) {
            echo MsgBox(_t('_sys_request_page_not_found_cpt')) . genAjaxyPopupJS($iEntryId, 'ajaxy_popup_result_div');
            exit;
        }

        if (!$this->isAllowedDelete($aDataEntry) || 0 != strcasecmp($_SERVER['REQUEST_METHOD'], 'POST')) {
            echo MsgBox(_t('_Access denied')) . genAjaxyPopupJS($iEntryId, 'ajaxy_popup_result_div');
            exit;
        }

        if ($this->_oDb->deleteEventByIdAndOwner($iGroupId, $iEntryId, $this->_iProfileId, $this->isAdmin())) {
            $this->isAllowedDelete($aDataEntry, true); // perform action
            $this->onEventEventDeleted ($iEntryId, $aDataEntry);            
            $sRedirect = BX_DOL_URL_ROOT . $this->_oConfig->getBaseUri() . 'view/' . $aDataEntry['uri'];
  
            $sJQueryJS = genAjaxyPopupJS($iEntryId, 'ajaxy_popup_result_div', $sRedirect);
            echo MsgBox(_t($sMsgSuccess)) . $sJQueryJS;
            exit;
        }

        echo MsgBox(_t('_Error Occured')) . genAjaxyPopupJS($iEntryId, 'ajaxy_popup_result_div');
        exit;
    }
 
    function actionEventAdd ($iGroupId, $sTitle) {
  
        if (!$this->isAllowedAdd()) {
            $this->_oTemplate->displayAccessDenied ();
            return;
        }
 
		if (!($aDataEntry = $this->_oDb->getEntryById($iGroupId))) {
			$this->_oTemplate->displayPageNotFound ();
			return;
		}	

        $this->_oTemplate->pageStart();

        $GLOBALS['oTopMenu']->setCustomSubHeader($aDataEntry[$this->_oDb->_sFieldTitle]);
        $GLOBALS['oTopMenu']->setCustomVar($this->_sPrefix.'_view_uri', $aDataEntry[$this->_oDb->_sFieldUri]);
		 
        $this->_addEventForm($iGroupId);

        $this->_oTemplate->addJs ('main.js');
        $this->_oTemplate->addCss ('main.css');
        $this->_oTemplate->addCss ('forms_extra.css');
        $this->_oTemplate->pageCode(_t($sTitle, $aDataEntry[$this->_oDb->_sFieldTitle]));  
    }
 
    function _addEventForm ($iGroupId) { 
 
        bx_import ('EventFormAdd', $this->_aModule);
        $sClass = $this->_aModule['class_prefix'] . 'EventFormAdd';
        $oForm = new $sClass ($this, $this->_iProfileId, $iGroupId);
        $oForm->initChecker();

        if ($oForm->isSubmittedAndValid ()) {
 
			$sStatus = 'approved';

            $this->_oDb->_sTableMain = 'event_main';
			$this->_oDb->_sFieldId = 'id';
			$this->_oDb->_sFieldUri = 'uri';
			$this->_oDb->_sFieldTitle = 'title';
			$this->_oDb->_sFieldDescription = 'desc'; 
			$this->_oDb->_sFieldThumb = 'thumb';
			$this->_oDb->_sFieldStatus = 'status'; 
			$this->_oDb->_sFieldCreated = 'created';
 
			$this->_oDb->_sTableMediaPrefix = $this->_oDb->_sTableEventMediaPrefix;
 
            $aValsAdd = array (
                $this->_oDb->_sFieldCreated => time(),
                $this->_oDb->_sFieldUri => $oForm->generateUri(),
                $this->_oDb->_sFieldStatus => $sStatus,
                $this->_oDb->_sFieldAuthorId => $this->_iProfileId 
            );                        
 
            $iEntryId = $oForm->insert ($aValsAdd);
 
            if ($iEntryId) {

                $this->isAllowedAdd(true); // perform action                 
 
				$oForm->processMedia($iEntryId, $this->_iProfileId); 
	  
                $aDataEntry = $this->_oDb->getEventEntryById($iEntryId);
    
				$sRedirectUrl = BX_DOL_URL_ROOT . $this->_oConfig->getBaseUri() . 'event/view/' . $aDataEntry[$this->_oDb->_sFieldUri];
			  
                header ('Location:' . $sRedirectUrl);
                exit;

            } else {

                MsgBox(_t('_Error Occured'));
            }
                         
        } else { 
            echo $oForm->getCode (); 
        }
    }
 

    function onEventEventDeleted ($iEntryId, $aDataEntry = array()) {

        // delete associated tags and categories 
        $this->reparseEventTags ($iEntryId);
        $this->reparseEventCategories ($iEntryId);

        // delete votings
        bx_import('EventVoting', $this->_aModule);
        $sClass = $this->_aModule['class_prefix'] . 'EventVoting';
        $oVoting = new $sClass ($this->_oDb->_sEventPrefix, 0, 0);
        $oVoting->deleteVotings ($iEntryId);

        // delete comments 
        bx_import('EventCmts', $this->_aModule);
        $sClass = $this->_aModule['class_prefix'] . 'EventCmts';
        $oCmts = new $sClass ($this->_oDb->_sEventPrefix, $iEntryId);
        $oCmts->onObjectDelete ();

        // delete views
        bx_import ('BxDolViews');
        $oViews = new BxDolViews($this->_oDb->_sEventPrefix, $iEntryId, false);
        $oViews->onObjectDelete();

 
        // arise alert
		//$oAlert = new BxDolAlerts($this->_sPrefix, 'delete', $iEntryId, $this->_iProfileId);
		//$oAlert->alert();
    }        


    /*******[END - EVENT Functions] ******************************/



    function actionPaypalFeaturedProcess($iProfileId, $iGroupId) {
    
        $aData = &$_REQUEST;

        if($aData) {
			$iQuantity = (int)$aData['quantity'];

			$aDataEntry = $this->_oDb->getEntryById($iGroupId); 
			$sRedirectUrl = BX_DOL_URL_ROOT . $this->_oConfig->getBaseUri() . 'view/' . $aDataEntry[$this->_oDb->_sFieldUri];
 
        	$sRequest = 'cmd=_notify-validate';
        	foreach($aData as $sKey => $sValue)
        		$sRequest .= '&' . urlencode($sKey) . '=' . urlencode( process_pass_data($sValue));

        	$aResponse = $this->_readValidationData($sRequest);
    
        	if((int)$aResponse['code'] !== 0){
 				$this->actionPurchaseFeatured(_t('_bx_groups_featured_purchase_failed')); 
 				return;
			}

        	array_walk($aResponse['content'], create_function('&$arg', "\$arg = trim(\$arg);"));
        	if(strcmp($aResponse['content'][0], "INVALID") == 0){
  				$this->actionPurchaseFeatured(_t('_payment_pp_err_wrong_transaction'));
 				return; 
        	}

			if(strcmp($aResponse['content'][0], "VERIFIED") != 0){
  				$this->actionPurchaseFeatured(_t('_payment_pp_err_wrong_verification_status'));
 				return;  
			}
  
			if($aData['txn_type'] != 'web_accept') {
				$this->actionPurchaseFeatured($iGroupId, _t('_bx_groups_featured_purchase_failed'));
			}else { 
				
				$fAmount = $this->_getReceivedAmount($aData);

				if($this->_oDb->isExistFeaturedTransaction($iProfileId, $aData['txn_id'])) {
					$this -> actionPurchaseFeatured($iGroupId, _t('_bx_groups_transaction_completed_already')); 
				} else {
					if( $this->_oDb->saveFeaturedTransactionRecord($iProfileId, $iGroupId,  $iQuantity, $fAmount, $aData['txn_id'], 'Paypal Purchase')) {

						$this->_oDb->updateFeaturedEntryExpiration($iGroupId, $iQuantity); 
			   
						$this->actionPurchaseFeatured($iGroupId, _t('_bx_groups_purchase_success',  $iQuantity));
					} else {
						$this -> actionPurchaseFeatured($iGroupId, _t('_bx_groups_trans_save_failed'));
					}
				}
			}
	 
		}
    }


	function _getReceivedAmount(&$aResultData) {
	    $fAmount = 0.00; 
		$sCurrencyCode = $this->_oConfig->getPurchaseCurrency();

    	if($aResultData['mc_currency'] == $sCurrencyCode && isset($aResultData['payment_gross']) && !empty($aResultData['payment_gross']))	
    		$fAmount = (float)$aResultData['payment_gross'];	
    	else if($aResultData['mc_currency'] == $sCurrencyCode && isset($aResultData['mc_gross']) && !empty($aResultData['mc_gross']))	
    		$fAmount = (float)$aResultData['mc_gross'];
    	else if($aResultData['settle_currency'] == $sCurrencyCode && isset($aResultData['settle_amount']) && !empty($aResultData['settle_amount']))	
    		$fAmount = (float)$aResultData['settle_amount'];

    	return $fAmount;
    }
 
    function _readValidationData($sRequest) {
        $sHeader = "POST /cgi-bin/webscr HTTP/1.0\r\n";
    	$sHeader .= "Host: www.paypal.com\r\n";
    	$sHeader .= "Content-Type: application/x-www-form-urlencoded\r\n";
    	$sHeader .= "Content-Length: " . strlen($sRequest) . "\r\n";
    	$sHeader .= "Connection: close\r\n\r\n";
    	
    	$iErrCode = 0;
    	$sErrMessage = "";
		$rSocket = fsockopen("ssl://www.paypal.com", 443, $iErrCode, $sErrMessage, 60);
 
    	if(!$rSocket)
    		return array('code' => 2, 'message' => 'Can\'t connect to remote host for validation (' . $sErrMessage . ')');

    	fputs($rSocket, $sHeader . $sRequest);
    	$sResponse = '';
        while(!feof($rSocket))
            $sResponse .= fread($rSocket, 1024);
    	fclose($rSocket);
      
    	$aResponse = explode("\r\n\r\n", $sResponse);
    	$sResponseHeader = $aResponse[0];
    	$sResponseContent = $aResponse[1];

    	return array('code' => 0, 'content' => explode("\n", $sResponseContent));
    }

	function initializeCheckout($iGroupId, $fTotalCost, $iQuantity=1, $bFeatured=0) {
  
		$aFormData = array(
			'cmd' => '_xclick',
			'amount' => sprintf( "%.2f", (float)$fTotalCost)
		);
    	 
		if($bFeatured){
			$sNotifyUrl = $this->_oConfig->getFeaturedCallbackUrl() . $this->_iProfileId .'/'. $iGroupId;
			$sItemDesc = getParam('bx_groups_featured_purchase_desc');
 		}

		$aDataEntry = $this->_oDb->getEntryById($iGroupId);
 		$sUri = $aDataEntry[$this->_oDb->_sFieldUri];

        $aFormData = array_merge($aFormData, array(
			'business' => getParam('bx_groups_paypal_email'), 
            'item_name' => $sItemDesc,
			'amount' => $fTotalCost, 
            'item_number' => $iGroupId,
            'quantity' => $iQuantity,
            'currency_code' => $this->_oConfig->getPurchaseCurrency(),
            'no_note' => '1',
            'no_shipping' => '1',  
			'return' => $this->_oConfig->getReturnUrl() . $sUri,
			'notify_url' => $sNotifyUrl,  
			'rm' => '1'
        ));
  
    	Redirect($this->_oConfig->getPurchaseBaseUrl(), $aFormData, 'post', "Feature Group");
    	exit();
	}
 

    function actionPurchaseFeatured($iGroupId, $sTransMessage = '') {
 
        if(! $this->_iProfileId) {
            header('location: ' . BX_DOL_URL_ROOT . 'member.php');
        }

	    if($sTransMessage){
			$sMessageOutput = MsgBox($sTransMessage);  
		}
 
		$iPerDayCost = getParam('bx_groups_featured_cost');

		$aDataEntry = $this->_oDb->getEntryById($iGroupId);
		$sTitle = $aDataEntry['title'];

        $this->_oTemplate->pageStart();
 
		$aForm = array(
            'form_attrs' => array(
                'name' => 'buy_featured_form',
                'method' => 'post', 
                'action' => BX_DOL_URL_ROOT . $this->_oConfig->getBaseUri() . 'purchase_featured/'.$iGroupId,
            ),
            'params' => array (
                'db' => array(
                    'submit_name' => 'submit_purchase',
                ),
            ),
            'inputs' => array( 
  
                'title' => array(
                    'type' => 'custom',
                    'name' => 'title',
					'caption'  => _t('_bx_groups_form_caption_title'),
                    'content' => $sTitle,
                ), 
                'cost' => array(
                    'type' => 'custom',
                    'name' => 'cost',
					'caption'  => _t('_bx_groups_featured_cost_per_day'),
                    'content' => $iPerDayCost .' '. $this->_oConfig->getPurchaseCurrency(),
                ), 
                'status' => array(
                    'type' => 'custom',
                    'name' => 'status',
					'caption'  => _t('_bx_groups_featured_status'),
                    'content' => ($aDataEntry['featured']) ? _t('_bx_groups_featured_until', $this->_oTemplate->filterDate($aDataEntry['featured_expiry_date'])) : _t('_bx_groups_not_featured'), 
                ),  
                'quantity' => array(
                    'caption'  => _t('_bx_groups_caption_num_featured_days'),
                    'type'   => 'text',
                    'name' => 'quantity',
                    'required' => true,
                    'checker' => array (  
                        'func'   => 'Preg',
                        'params' => array('/^[0-9]+$/'),
                        'error'  => _t('_bx_groups_caption_err_featured_days'),
                    ),
                ),
                'submit' => array(
                    'type'  => 'submit',
                    'value' => ($aDataEntry['featured']) ? _t('_bx_groups_extend_featured') : _t('_bx_groups_get_featured'),
                    'name'  => 'submit_purchase',
                ),
            ),
        );
        $oForm = new BxTemplFormView($aForm);
        $oForm->initChecker();  

        if ($oForm->isSubmittedAndValid() && $oForm->getCleanValue('quantity')) { 
 
			$fCost =  number_format($iPerDayCost, 2); 

            //header('location:' . $this->_oDb->generateFeaturedPaymentUrl($iGroupId, $oForm->getCleanValue('quantity'), $fCost));

			$this->initializeCheckout($iGroupId, $fCost, $oForm->getCleanValue('quantity'), true);  
			return; 
        } else {
             echo $sMessageOutput . $oForm->getCode();
        }

        $this->_oTemplate->addCss ('main.css'); 
        $this->_oTemplate->addCss ('paid.css'); 
        $this->_oTemplate->pageCode(_t('_bx_groups_purchase_featured')); 
    }
  
    function isAllowedPurchaseFeatured ($aDataEntry, $isPerformAction = false) {

		if(getParam("bx_groups_buy_featured")!='on')
			return false;
 
		if($aDataEntry['author_id'] != $this->_iProfileId)
			return false;
 
        $this->_defineActions();
        $aCheck = checkAction($this->_iProfileId, BX_GROUPS_PURCHASE_FEATURED, $isPerformAction);
        return $aCheck[CHECK_ACTION_RESULT] == CHECK_ACTION_RESULT_ALLOWED;        
    } 

	function actionMapMultiple($iCenterLat=0, $iCenterLng=0, $iRadius=0){
   
		// Get parameters from URL
		//$iCenterLat = $_GET["lat"];
		//$iCenterLng = $_GET["lng"];
		//$iRadius = $_GET["radius"];

		// Start XML file, create parent node
		$dom = new DOMDocument("1.0");
		$node = $dom->createElement("markers");
		$parnode = $dom->appendChild($node);

		$iCount = (int)getParam('bx_groups_map_count');
		$sMeasurementType = getParam('bx_groups_measurement_type');

		switch($sMeasurementType){
			case 'miles':
				$iCalcValue = 3959;
			break;
			case 'kilometers':
				$iCalcValue = 6371;
			break;
			default:
				$iCalcValue = 6371;
			break;
		}
  
		// Search the rows in the markers table
		$query = sprintf("SELECT `p`.`title`, `p`.`uri`, `p`.`city`, `p`.`country`, `p`.`thumb`, `m`.`lat`, `m`.`lng`, ( %s * acos( cos( radians('%s') ) * cos( radians( `m`.`lat` ) ) * cos( radians( `m`.`lng` ) - radians('%s') ) + sin( radians('%s') ) * sin( radians( `m`.`lat` ) ) ) ) AS distance FROM `bx_groups_profiles` AS `m` INNER JOIN `bx_groups_main` AS `p` ON (`p`.`id` = `m`.`id`) WHERE `m`.`failed` = 0 AND `p`.`status` = 'approved' HAVING distance < '%s' ORDER BY distance LIMIT 0 , %s",
		  $iCalcValue,
		  mysql_real_escape_string($iCenterLat),
		  mysql_real_escape_string($iCenterLng),
		  mysql_real_escape_string($iCenterLat),
		  mysql_real_escape_string($iRadius),
		  $iCount);
		$result = db_res($query);
 
		header("Content-type: text/xml");

		// Iterate through the rows, adding XML nodes for each
		while ($row = @mysql_fetch_assoc($result)){
			  $node = $dom->createElement("marker");
			  $newnode = $parnode->appendChild($node);
			  
			  $sCountry = _t($GLOBALS['aPreValues']['Country'][$row['country']]['LKey']);
			  $sCity = $row['city'];
			  $sAddress = $sCity .', '. $sCountry;
			  
			  $newnode->setAttribute("url", 'm/groups/view/'.$row['uri']);
			  $newnode->setAttribute("name", $row['title']);
			  $newnode->setAttribute("address", $sAddress);
			  $newnode->setAttribute("lat", $row['lat']);
			  $newnode->setAttribute("lng", $row['lng']);
			  $newnode->setAttribute("distance", $row['distance']);
		}
 
		echo $dom->saveXML();
		exit;
	}
 
	function actionMapSingle($iItemId){
    
		// Start XML file, create parent node
		$dom = new DOMDocument("1.0");
		$node = $dom->createElement("markers");
		$parnode = $dom->appendChild($node);
  
		// Search the rows in the markers table
  
		$query = sprintf("SELECT `p`.`title`, `p`.`uri`, `p`.`city`, `p`.`country`, `p`.`thumb`, `m`.`lat`, `m`.`lng`, `p`.`city` FROM `bx_groups_profiles` AS `m` INNER JOIN `bx_groups_main` AS `p` ON (`p`.`id` = `m`.`id`) WHERE `m`.`failed` = 0 AND `p`.`status` = 'approved' AND `m`.`id` = '%s'", 
		  mysql_real_escape_string($iItemId)); 
		$result = db_res($query);


		header("Content-type: text/xml");

		// Iterate through the rows, adding XML nodes for each
		while ($row = @mysql_fetch_assoc($result)){
			  $node = $dom->createElement("marker");
			  $newnode = $parnode->appendChild($node);

			  $sCountry = _t($GLOBALS['aPreValues']['Country'][$row['country']]['LKey']);
			  $sCity = $row['city'];
			  $sAddress = $sCity .', '. $sCountry;

			  $newnode->setAttribute("url", 'm/groups/view/'.$row['uri']);
			  $newnode->setAttribute("name", $row['title']);
			  $newnode->setAttribute("address", $sAddress);
			  $newnode->setAttribute("lat", $row['lat']);
			  $newnode->setAttribute("lng", $row['lng']);
		  
		}

		echo $dom->saveXML(); 
	}
 





}

?>